<script lang="ts">
  import type { OpportunityProduct } from "../types";
  import NoResultsMonkey from "../../../../../components/NoResultsMonkey.svelte";

  export let products: OpportunityProduct[] = [];

  $: discountedProducts = products.filter(
    (p) => (p.discount ?? 0) !== 0 && !p.cancelled
  );

  $: totalDiscount = discountedProducts.reduce(
    (sum, p) => sum + (p.discount ?? 0) * (p.quantity ?? 1),
    0
  );

  $: totalListPrice = discountedProducts.reduce(
    (sum, p) => sum + (p.listPrice ?? 0) * (p.quantity ?? 1),
    0
  );

  $: totalUnitPrice = discountedProducts.reduce(
    (sum, p) => sum + (p.unitPrice ?? 0) * (p.quantity ?? 1),
    0
  );

  function fmtMoney(value: number): string {
    return value.toLocaleString("en-US", {
      style: "currency",
      currency: "USD",
    });
  }

  function fmtPercent(list: number, discount: number): string {
    if (list === 0) return "—";
    const pct = (discount / list) * 100;
    return `${pct.toFixed(1)}%`;
  }
</script>

<div class="discounts-tab">
  <!-- Summary cards -->
  {#if discountedProducts.length > 0}
    <div class="discounts-summary">
      <div class="discount-summary-card">
        <span class="discount-summary-label">Total List Price</span>
        <span class="discount-summary-value">{fmtMoney(totalListPrice)}</span>
      </div>
      <div class="discount-summary-card">
        <span class="discount-summary-label">Total Discounts</span>
        <span class="discount-summary-value discount-negative"
          >{fmtMoney(totalDiscount)}</span
        >
      </div>
      <div class="discount-summary-card">
        <span class="discount-summary-label">Net Price</span>
        <span class="discount-summary-value">{fmtMoney(totalUnitPrice)}</span>
      </div>
    </div>
  {/if}

  <!-- Discounts table -->
  {#if discountedProducts.length === 0}
    <div class="tab-empty">
      <NoResultsMonkey message="No discounts applied" />
    </div>
  {:else}
    <div class="discounts-table-wrap">
      <table class="discounts-table">
        <thead>
          <tr>
            <th class="col-product">Product</th>
            <th class="col-num">Qty</th>
            <th class="col-num">List Price</th>
            <th class="col-num">Discount</th>
            <th class="col-num">% Off</th>
            <th class="col-num">Unit Price</th>
            <th class="col-num">Ext. Discount</th>
          </tr>
        </thead>
        <tbody>
          {#each discountedProducts as product (product.id)}
            <tr>
              <td class="col-product">
                <div class="discount-product-name">
                  {product.forecastDescription || product.productDescription || "—"}
                </div>
                {#if product.catalogItem?.identifier}
                  <div class="discount-product-sku">
                    {product.catalogItem.identifier}
                  </div>
                {/if}
              </td>
              <td class="col-num">{product.quantity ?? 0}</td>
              <td class="col-num">{fmtMoney(product.listPrice ?? 0)}</td>
              <td class="col-num discount-negative">
                {fmtMoney(product.discount ?? 0)}
              </td>
              <td class="col-num">
                {fmtPercent(product.listPrice ?? 0, product.discount ?? 0)}
              </td>
              <td class="col-num">{fmtMoney(product.unitPrice ?? 0)}</td>
              <td class="col-num discount-negative">
                {fmtMoney((product.discount ?? 0) * (product.quantity ?? 1))}
              </td>
            </tr>
          {/each}
        </tbody>
        <tfoot>
          <tr>
            <td class="col-product"><strong>Total</strong></td>
            <td class="col-num"></td>
            <td class="col-num"><strong>{fmtMoney(totalListPrice)}</strong></td>
            <td class="col-num discount-negative">
              <strong>{fmtMoney(totalDiscount)}</strong>
            </td>
            <td class="col-num">
              {fmtPercent(totalListPrice, totalDiscount)}
            </td>
            <td class="col-num"><strong>{fmtMoney(totalUnitPrice)}</strong></td>
            <td class="col-num discount-negative">
              <strong>{fmtMoney(totalDiscount)}</strong>
            </td>
          </tr>
        </tfoot>
      </table>
    </div>
  {/if}
</div>

<style>
  .discounts-tab {
    display: flex;
    flex-direction: column;
    gap: 16px;
    padding: 16px 0;
  }

  .discounts-summary {
    display: flex;
    gap: 12px;
    padding: 0 16px;
  }

  .discount-summary-card {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 4px;
    padding: 12px 16px;
    border-radius: 8px;
    background: var(--bg-raised, #f7f8fa);
    border: 1px solid var(--border-subtle, #e2e5ea);
  }

  .discount-summary-label {
    font-size: 0.75rem;
    font-weight: 500;
    color: var(--text-muted, #6b7280);
    text-transform: uppercase;
    letter-spacing: 0.03em;
  }

  .discount-summary-value {
    font-size: 1.25rem;
    font-weight: 600;
    color: var(--text-primary, #1a1a2e);
    font-variant-numeric: tabular-nums;
  }

  .discount-negative {
    color: var(--color-danger, #dc2626);
  }

  .discounts-table-wrap {
    overflow-x: auto;
    padding: 0 16px;
  }

  .discounts-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 0.875rem;
  }

  .discounts-table th {
    text-align: left;
    padding: 8px 12px;
    font-weight: 600;
    font-size: 0.75rem;
    text-transform: uppercase;
    letter-spacing: 0.03em;
    color: var(--text-muted, #6b7280);
    border-bottom: 2px solid var(--border-subtle, #e2e5ea);
    white-space: nowrap;
  }

  .discounts-table td {
    padding: 10px 12px;
    border-bottom: 1px solid var(--border-subtle, #e2e5ea);
    vertical-align: middle;
  }

  .discounts-table tbody tr:last-child td {
    border-bottom: none;
  }

  .discounts-table tbody tr:hover {
    background: var(--bg-hover, rgba(0, 0, 0, 0.02));
  }

  .discounts-table tfoot td {
    padding: 10px 12px;
    border-top: 2px solid var(--border-subtle, #e2e5ea);
    font-weight: 600;
  }

  .col-product {
    min-width: 200px;
  }

  .col-num {
    text-align: right;
    font-variant-numeric: tabular-nums;
    white-space: nowrap;
  }

  .discounts-table th.col-num {
    text-align: right;
  }

  .discount-product-name {
    font-weight: 500;
    color: var(--text-primary, #1a1a2e);
  }

  .discount-product-sku {
    font-size: 0.75rem;
    color: var(--text-muted, #6b7280);
    margin-top: 2px;
  }

  @media (max-width: 768px) {
    .discounts-summary {
      flex-direction: column;
    }
  }
</style>
