<p-toast />

<div class="sales-reports-page">
  <app-page-header title="SALES.REPORTS" subtitle="SALES.TITLE" (refresh)="retry()">
  </app-page-header>

  <!-- Filter Bar -->
  <div class="filter-bar">
    <p-datepicker
      [(ngModel)]="dateRange"
      selectionMode="range"
      [placeholder]="'COMMON.DATE_RANGE' | translate"
      dateFormat="yy-mm-dd"
      [showIcon]="true"
      styleClass="filter-input"
    />
    <p-button
      [label]="'SALES.GENERATE_REPORT' | translate"
      icon="pi pi-search"
      (onClick)="generateReport()"
    />
  </div>

  <p-tabs [value]="activeTab()" (valueChange)="onTabChange($any($event))">
    <p-tablist>
      <p-tab value="summary">{{ 'SALES.SUMMARY' | translate }}</p-tab>
      <p-tab value="product">{{ 'SALES.BY_PRODUCT' | translate }}</p-tab>
      <p-tab value="customer">{{ 'SALES.BY_CUSTOMER' | translate }}</p-tab>
      <p-tab value="salesperson">{{ 'SALES.BY_SALESPERSON' | translate }}</p-tab>
      <p-tab value="trends">{{ 'SALES.TRENDS' | translate }}</p-tab>
      <p-tab value="overdue">{{ 'SALES.OVERDUE' | translate }}</p-tab>
      <p-tab value="funnel">{{ 'SALES.CONVERSION_FUNNEL' | translate }}</p-tab>
    </p-tablist>
    <p-tabpanels>
      <!-- ─── Summary ───────────────────────── -->
      <p-tabpanel value="summary">
        @if (loading()) {
          <div class="loading-wrap"><p-progressSpinner strokeWidth="3" animationDuration="1s" /></div>
        } @else {
          <div class="stat-cards">
            <div class="stat-mini"><span class="stat-num">{{ getSummaryValue('quotations_count') }}</span><span class="stat-lbl">{{ 'SALES.QUOTATIONS' | translate }}</span><span class="stat-val">{{ getSummaryValue('quotations_value') | number:'1.0-0' }}</span></div>
            <div class="stat-mini"><span class="stat-num">{{ getSummaryValue('orders_count') }}</span><span class="stat-lbl">{{ 'SALES.ORDERS' | translate }}</span><span class="stat-val">{{ getSummaryValue('orders_value') | number:'1.0-0' }}</span></div>
            <div class="stat-mini"><span class="stat-num">{{ getSummaryValue('invoices_count') }}</span><span class="stat-lbl">{{ 'SALES.INVOICES' | translate }}</span><span class="stat-val">{{ getSummaryValue('invoices_value') | number:'1.0-0' }}</span></div>
            <div class="stat-mini"><span class="stat-num">{{ getSummaryValue('returns_count') }}</span><span class="stat-lbl">{{ 'SALES.RETURNS' | translate }}</span><span class="stat-val">{{ getSummaryValue('returns_value') | number:'1.0-0' }}</span></div>
            <div class="stat-mini highlight"><span class="stat-num">{{ getSummaryValue('net_sales') | number:'1.0-0' }}</span><span class="stat-lbl">{{ 'SALES.NET_SALES' | translate }}</span></div>
            <div class="stat-mini"><span class="stat-num">{{ getSummaryValue('amount_collected') | number:'1.0-0' }}</span><span class="stat-lbl">{{ 'SALES.COLLECTED' | translate }}</span></div>
            <div class="stat-mini"><span class="stat-num">{{ getSummaryValue('amount_outstanding') | number:'1.0-0' }}</span><span class="stat-lbl">{{ 'SALES.OUTSTANDING' | translate }}</span></div>
          </div>
          @if (summaryChart()) {
            <div class="chart-wrap">
              <p-chart type="bar" [data]="summaryChart()" [options]="barOptions" [style]="{'height':'300px'}" />
            </div>
          }
        }
      </p-tabpanel>

      <!-- ─── By Product ────────────────────── -->
      <p-tabpanel value="product">
        @if (loading()) {
          <div class="loading-wrap"><p-progressSpinner strokeWidth="3" animationDuration="1s" /></div>
        } @else {
          @if (productChart()) {
            <div class="chart-wrap">
              <h4>{{ 'SALES.TOP_10_PRODUCTS' | translate }}</h4>
              <p-chart type="bar" [data]="productChart()" [options]="horizontalBarOptions" [style]="{'height':'300px'}" />
            </div>
          }
          <div class="table-toolbar">
            <p-button icon="pi pi-file-excel" [label]="'COMMON.EXPORT' | translate" severity="success" size="small" (onClick)="exportExcel(productData(), 'sales-by-product')" />
          </div>
          <p-table [value]="productData()" [paginator]="true" [rows]="25" styleClass="p-datatable-sm p-datatable-striped" [sortMode]="'single'">
            <ng-template #header>
              <tr>
                <th pSortableColumn="product_name">{{ 'SALES.PRODUCT' | translate }} <p-sortIcon field="product_name" /></th>
                <th>{{ 'SALES.SKU' | translate }}</th>
                <th pSortableColumn="quantity_sold">{{ 'SALES.QTY_SOLD' | translate }} <p-sortIcon field="quantity_sold" /></th>
                <th pSortableColumn="total_sales">{{ 'SALES.REVENUE' | translate }} <p-sortIcon field="total_sales" /></th>
                <th pSortableColumn="gross_profit">{{ 'SALES.GROSS_PROFIT' | translate }} <p-sortIcon field="gross_profit" /></th>
                <th>{{ 'SALES.MARGIN' | translate }}</th>
              </tr>
            </ng-template>
            <ng-template #body let-row>
              <tr>
                <td>{{ row.product_name || row.name }}</td>
                <td class="mono">{{ row.product_code || row.sku }}</td>
                <td class="amount">{{ row.quantity_sold }}</td>
                <td class="amount">{{ (row.total_sales || row.gross_revenue || row.net_revenue || 0) | number:'1.2-2' }}</td>
                <td class="amount">{{ (row.gross_profit || 0) | number:'1.2-2' }}</td>
                <td class="amount">{{ row.profit_margin || row.margin_percent || 0 }}%</td>
              </tr>
            </ng-template>
            <ng-template #emptymessage><tr><td colspan="6" class="text-center">{{ 'COMMON.NO_DATA' | translate }}</td></tr></ng-template>
          </p-table>
        }
      </p-tabpanel>

      <!-- ─── By Customer ───────────────────── -->
      <p-tabpanel value="customer">
        @if (loading()) {
          <div class="loading-wrap"><p-progressSpinner strokeWidth="3" animationDuration="1s" /></div>
        } @else {
          @if (customerChart()) {
            <div class="chart-wrap">
              <h4>{{ 'SALES.TOP_CUSTOMERS' | translate }}</h4>
              <p-chart type="bar" [data]="customerChart()" [options]="horizontalBarOptions" [style]="{'height':'300px'}" />
            </div>
          }
          <div class="table-toolbar">
            <p-button icon="pi pi-file-excel" [label]="'COMMON.EXPORT' | translate" severity="success" size="small" (onClick)="exportExcel(customerData(), 'sales-by-customer')" />
          </div>
          <p-table [value]="customerData()" [paginator]="true" [rows]="25" styleClass="p-datatable-sm p-datatable-striped" [sortMode]="'single'">
            <ng-template #header>
              <tr>
                <th pSortableColumn="customer_name">{{ 'SALES.CUSTOMER' | translate }} <p-sortIcon field="customer_name" /></th>
                <th>{{ 'SALES.INVOICES' | translate }}</th>
                <th pSortableColumn="total_sales">{{ 'SALES.REVENUE' | translate }} <p-sortIcon field="total_sales" /></th>
                <th>{{ 'SALES.RETURNS' | translate }}</th>
                <th pSortableColumn="net_sales">{{ 'SALES.NET_SALES' | translate }} <p-sortIcon field="net_sales" /></th>
                <th>{{ 'SALES.OUTSTANDING' | translate }}</th>
              </tr>
            </ng-template>
            <ng-template #body let-row>
              <tr>
                <td>{{ row.customer_name || row.name }}</td>
                <td class="amount">{{ row.invoices_count || row.invoice_count || 0 }}</td>
                <td class="amount">{{ (row.total_sales || row.gross_revenue || 0) | number:'1.2-2' }}</td>
                <td class="amount">{{ (row.total_returns || 0) | number:'1.2-2' }}</td>
                <td class="amount">{{ (row.net_sales || row.gross_revenue || 0) | number:'1.2-2' }}</td>
                <td class="amount">{{ (row.balance_due || row.outstanding_balance || 0) | number:'1.2-2' }}</td>
              </tr>
            </ng-template>
            <ng-template #emptymessage><tr><td colspan="6" class="text-center">{{ 'COMMON.NO_DATA' | translate }}</td></tr></ng-template>
          </p-table>
        }
      </p-tabpanel>

      <!-- ─── By Salesperson ────────────────── -->
      <p-tabpanel value="salesperson">
        @if (loading()) {
          <div class="loading-wrap"><p-progressSpinner strokeWidth="3" animationDuration="1s" /></div>
        } @else {
          @if (salespersonChart()) {
            <div class="chart-wrap">
              <p-chart type="bar" [data]="salespersonChart()" [options]="horizontalBarOptions" [style]="{'height':'300px'}" />
            </div>
          }
          <div class="table-toolbar">
            <p-button icon="pi pi-file-excel" [label]="'COMMON.EXPORT' | translate" severity="success" size="small" (onClick)="exportExcel(salespersonData(), 'sales-by-salesperson')" />
          </div>
          <p-table [value]="salespersonData()" [paginator]="true" [rows]="25" styleClass="p-datatable-sm p-datatable-striped">
            <ng-template #header>
              <tr>
                <th>{{ 'SALES.SALESPERSON' | translate }}</th>
                <th>{{ 'SALES.INVOICES' | translate }}</th>
                <th>{{ 'SALES.REVENUE' | translate }}</th>
                <th>{{ 'SALES.COMMISSIONS' | translate }}</th>
              </tr>
            </ng-template>
            <ng-template #body let-row>
              <tr>
                <td>{{ row.salesperson_name || row.name }}</td>
                <td class="amount">{{ row.invoices_count || row.count }}</td>
                <td class="amount">{{ (row.total_sales || row.revenue || 0) | number:'1.2-2' }}</td>
                <td class="amount">{{ (row.total_commissions || row.commissions || 0) | number:'1.2-2' }}</td>
              </tr>
            </ng-template>
            <ng-template #emptymessage><tr><td colspan="4" class="text-center">{{ 'COMMON.NO_DATA' | translate }}</td></tr></ng-template>
          </p-table>
        }
      </p-tabpanel>

      <!-- ─── Trends ────────────────────────── -->
      <p-tabpanel value="trends">
        @if (loading()) {
          <div class="loading-wrap"><p-progressSpinner strokeWidth="3" animationDuration="1s" /></div>
        } @else {
          @if (trendsChart()) {
            <div class="chart-wrap chart-wide">
              <p-chart type="line" [data]="trendsChart()" [options]="lineOptions" [style]="{'height':'350px'}" />
            </div>
          } @else {
            <div class="no-data">{{ 'COMMON.NO_DATA' | translate }}</div>
          }
        }
      </p-tabpanel>

      <!-- ─── Overdue ───────────────────────── -->
      <p-tabpanel value="overdue">
        @if (loading()) {
          <div class="loading-wrap"><p-progressSpinner strokeWidth="3" animationDuration="1s" /></div>
        } @else {
          @if (agingBuckets()) {
            <div class="aging-cards">
              <div class="aging-card"><span class="aging-label">{{ 'SALES.CURRENT' | translate }}</span><span class="aging-val">{{ getAgingValue('current') | number:'1.0-0' }}</span></div>
              <div class="aging-card warn"><span class="aging-label">1-30 {{ 'SALES.DAYS' | translate }}</span><span class="aging-val">{{ getAgingValue('1_30') | number:'1.0-0' }}</span></div>
              <div class="aging-card danger"><span class="aging-label">31-60 {{ 'SALES.DAYS' | translate }}</span><span class="aging-val">{{ getAgingValue('31_60') | number:'1.0-0' }}</span></div>
              <div class="aging-card danger"><span class="aging-label">61-90 {{ 'SALES.DAYS' | translate }}</span><span class="aging-val">{{ getAgingValue('61_90') | number:'1.0-0' }}</span></div>
              <div class="aging-card critical"><span class="aging-label">90+ {{ 'SALES.DAYS' | translate }}</span><span class="aging-val">{{ getAgingValue('90_plus') | number:'1.0-0' }}</span></div>
            </div>
          }
          <div class="table-toolbar">
            <p-button icon="pi pi-file-excel" [label]="'COMMON.EXPORT' | translate" severity="success" size="small" (onClick)="exportExcel(overdueData(), 'overdue-invoices')" />
          </div>
          <p-table [value]="overdueData()" [paginator]="true" [rows]="25" styleClass="p-datatable-sm p-datatable-striped" [sortMode]="'single'">
            <ng-template #header>
              <tr>
                <th>{{ 'SALES.INVOICE_NUMBER' | translate }}</th>
                <th pSortableColumn="customer_name">{{ 'SALES.CUSTOMER' | translate }} <p-sortIcon field="customer_name" /></th>
                <th>{{ 'SALES.DATE' | translate }}</th>
                <th>{{ 'SALES.DUE_DATE' | translate }}</th>
                <th pSortableColumn="balance_due">{{ 'SALES.BALANCE_DUE' | translate }} <p-sortIcon field="balance_due" /></th>
                <th pSortableColumn="days_overdue">{{ 'SALES.DAYS_OVERDUE' | translate }} <p-sortIcon field="days_overdue" /></th>
              </tr>
            </ng-template>
            <ng-template #body let-row>
              <tr>
                <td class="mono">{{ row.invoice_number }}</td>
                <td>{{ row.customer_name }}</td>
                <td>{{ row.date }}</td>
                <td>{{ row.due_date }}</td>
                <td class="amount">{{ row.balance_due | number:'1.2-2' }}</td>
                <td><p-tag [value]="row.days_overdue + ''" severity="danger" /></td>
              </tr>
            </ng-template>
            <ng-template #emptymessage><tr><td colspan="6" class="text-center">{{ 'SALES.NO_OVERDUE' | translate }}</td></tr></ng-template>
          </p-table>
        }
      </p-tabpanel>

      <!-- ─── Funnel ────────────────────────── -->
      <p-tabpanel value="funnel">
        @if (loading()) {
          <div class="loading-wrap"><p-progressSpinner strokeWidth="3" animationDuration="1s" /></div>
        } @else if (funnelData()) {
          <div class="funnel-stats">
            <div class="funnel-step">
              <span class="funnel-count">{{ funnelData().total_quotations || funnelData().quotations_created || 0 }}</span>
              <span class="funnel-label">{{ 'SALES.QUOTATIONS' | translate }}</span>
            </div>
            <i class="pi pi-arrow-right funnel-arrow"></i>
            <div class="funnel-step">
              <span class="funnel-count">{{ funnelData().total_orders || funnelData().converted_to_orders || 0 }}</span>
              <span class="funnel-label">{{ 'SALES.ORDERS' | translate }}</span>
              <span class="funnel-rate">{{ funnelData().quotation_to_order_rate || funnelData().conversion_rate_to_order || 0 }}%</span>
            </div>
            <i class="pi pi-arrow-right funnel-arrow"></i>
            <div class="funnel-step">
              <span class="funnel-count">{{ funnelData().total_invoices || funnelData().converted_to_invoices || 0 }}</span>
              <span class="funnel-label">{{ 'SALES.INVOICES' | translate }}</span>
              <span class="funnel-rate">{{ funnelData().order_to_invoice_rate || funnelData().conversion_rate_to_invoice || 0 }}%</span>
            </div>
          </div>
          @if (funnelChart()) {
            <div class="chart-wrap">
              <p-chart type="bar" [data]="funnelChart()" [options]="barOptions" [style]="{'height':'300px'}" />
            </div>
          }
        } @else {
          <div class="no-data">{{ 'COMMON.NO_DATA' | translate }}</div>
        }
      </p-tabpanel>
    </p-tabpanels>
  </p-tabs>
</div>
