<p-toast />
<div class="stock-card-page">
  @if (loading()) {
    <div class="loading-state">
      <i class="pi pi-spin pi-spinner" style="font-size:2.5rem"></i>
      <p>{{ 'COMMON.LOADING' | translate }}</p>
    </div>
  } @else {
    <!-- Header -->
    <div class="page-header-bar">
      <div class="header-right">
        <p-button icon="pi pi-arrow-left" [label]="'INVENTORY.BACK_TO_BALANCES' | translate"
          severity="secondary" [outlined]="true" (onClick)="goBack()" />
        <div class="product-info">
          <h2>{{ product()?.name || '' }}@if (variantName) { <span class="variant-badge">{{ variantName }}</span>}</h2>
          <span class="product-code">{{ product()?.code }} — {{ product()?.category?.name || '' }}</span>
        </div>
      </div>
    </div>

    <!-- Stats & Charts (collapsible) -->
    <div class="collapsible-section" [class.collapsed]="statsCollapsed()">
      <button class="collapse-toggle" (click)="statsCollapsed.set(!statsCollapsed())">
        <i class="pi" [class.pi-chevron-down]="statsCollapsed()" [class.pi-chevron-up]="!statsCollapsed()"></i>
        <span>{{ 'INVENTORY.STATISTICS' | translate }}</span>
        <span class="collapse-summary" *ngIf="statsCollapsed()">
          {{ 'INVENTORY.CURRENT_BALANCE' | translate }}: <strong>{{ currentBalance() | number:'1.2-2' }}</strong>
          &nbsp;|&nbsp;
          {{ 'INVENTORY.TOTAL_IN' | translate }}: <strong>{{ totalIn() | number:'1.2-2' }}</strong>
          &nbsp;|&nbsp;
          {{ 'INVENTORY.TOTAL_OUT' | translate }}: <strong>{{ totalOut() | number:'1.2-2' }}</strong>
        </span>
      </button>
      @if (!statsCollapsed()) {
      <!-- Stats Cards -->
      <div class="stats-grid">
        <div class="stat-card stat-blue">
          <div class="stat-icon-wrap"><i class="pi pi-box"></i></div>
          <div class="stat-info">
            <span class="stat-value">{{ currentBalance() | number:'1.2-2' }}</span>
            <span class="stat-label">{{ 'INVENTORY.CURRENT_BALANCE' | translate }}</span>
          </div>
          <div class="stat-decoration"></div>
        </div>
        <div class="stat-card stat-green">
          <div class="stat-icon-wrap"><i class="pi pi-download"></i></div>
          <div class="stat-info">
            <span class="stat-value">{{ totalIn() | number:'1.2-2' }}</span>
            <span class="stat-label">{{ 'INVENTORY.TOTAL_IN' | translate }}</span>
          </div>
          <div class="stat-decoration"></div>
        </div>
        <div class="stat-card stat-rose">
          <div class="stat-icon-wrap"><i class="pi pi-upload"></i></div>
          <div class="stat-info">
            <span class="stat-value">{{ totalOut() | number:'1.2-2' }}</span>
            <span class="stat-label">{{ 'INVENTORY.TOTAL_OUT' | translate }}</span>
          </div>
          <div class="stat-decoration"></div>
        </div>
        <div class="stat-card stat-purple">
          <div class="stat-icon-wrap"><i class="pi pi-calculator"></i></div>
          <div class="stat-info">
            <span class="stat-value">{{ avgCost() | number:'1.2-2' }}</span>
            <span class="stat-label">{{ 'INVENTORY.AVG_COST' | translate }}</span>
          </div>
          <div class="stat-decoration"></div>
        </div>
        <div class="stat-card stat-amber">
          <div class="stat-icon-wrap"><i class="pi pi-dollar"></i></div>
          <div class="stat-info">
            <span class="stat-value">{{ totalValue() | number:'1.2-2' }}</span>
            <span class="stat-label">{{ 'INVENTORY.TOTAL_VALUE' | translate }}</span>
          </div>
          <div class="stat-decoration"></div>
        </div>
      </div>

      <!-- Charts Row 1 -->
      <div class="charts-row">
        <div class="chart-card">
          <div class="chart-header">
            <div class="chart-title-wrap">
              <div class="chart-icon" style="background:rgba(99,102,241,0.1)">
                <i class="pi pi-chart-line" style="color:#6366f1"></i>
              </div>
              <div>
                <h3>{{ 'INVENTORY.BALANCE_OVER_TIME' | translate }}</h3>
              </div>
            </div>
          </div>
          <div class="chart-body">
            @if (balanceChartData()) {
              <p-chart type="line" [data]="balanceChartData()" [options]="balanceChartOptions" height="280px" />
            } @else {
              <div class="no-chart-data">{{ 'COMMON.NO_DATA' | translate }}</div>
            }
          </div>
        </div>
        <div class="chart-card">
          <div class="chart-header">
            <div class="chart-title-wrap">
              <div class="chart-icon" style="background:rgba(16,185,129,0.1)">
                <i class="pi pi-chart-bar" style="color:#10b981"></i>
              </div>
              <div>
                <h3>{{ 'INVENTORY.MONTHLY_IN_OUT' | translate }}</h3>
              </div>
            </div>
          </div>
          <div class="chart-body">
            @if (monthlyChartData()) {
              <p-chart type="bar" [data]="monthlyChartData()" [options]="monthlyChartOptions" height="280px" />
            } @else {
              <div class="no-chart-data">{{ 'COMMON.NO_DATA' | translate }}</div>
            }
          </div>
        </div>
      </div>

      <!-- Charts Row 2 -->
      <div class="charts-row">
        <div class="chart-card">
          <div class="chart-header">
            <div class="chart-title-wrap">
              <div class="chart-icon" style="background:rgba(236,72,153,0.1)">
                <i class="pi pi-chart-pie" style="color:#ec4899"></i>
              </div>
              <div>
                <h3>{{ 'INVENTORY.MOVEMENT_TYPES' | translate }}</h3>
              </div>
            </div>
          </div>
          <div class="chart-body doughnut-chart">
            @if (movementChartData()) {
              <p-chart type="doughnut" [data]="movementChartData()" [options]="movementChartOptions" height="280px" width="280px" />
            } @else {
              <div class="no-chart-data">{{ 'COMMON.NO_DATA' | translate }}</div>
            }
          </div>
        </div>
        <div class="chart-card">
          <div class="chart-header">
            <div class="chart-title-wrap">
              <div class="chart-icon" style="background:rgba(99,102,241,0.1)">
                <i class="pi pi-building" style="color:#6366f1"></i>
              </div>
              <div>
                <h3>{{ 'INVENTORY.QTY_BY_WAREHOUSE' | translate }}</h3>
              </div>
            </div>
          </div>
          <div class="chart-body">
            @if (warehouseChartData()) {
              <p-chart type="bar" [data]="warehouseChartData()" [options]="warehouseChartOptions" height="280px" />
            } @else {
              <div class="no-chart-data">{{ 'COMMON.NO_DATA' | translate }}</div>
            }
          </div>
        </div>
      </div>
      }
    </div>

    <!-- Warehouse Breakdown Table -->
    <div class="section-card">
      <div class="section-header">
        <h3><i class="pi pi-building"></i> {{ 'INVENTORY.WAREHOUSE_BREAKDOWN' | translate }}</h3>
      </div>
      <p-table [value]="balances()" styleClass="p-datatable-sm p-datatable-gridlines">
        <ng-template #header>
          <tr>
            <th>{{ 'INVENTORY.WAREHOUSE' | translate }}</th>
            <th class="text-end">{{ 'INVENTORY.QUANTITY' | translate }}</th>
            <th class="text-end">{{ 'INVENTORY.AVAILABLE_QTY' | translate }}</th>
            <th class="text-end">{{ 'INVENTORY.AVG_COST' | translate }}</th>
            <th class="text-end">{{ 'INVENTORY.TOTAL_VALUE' | translate }}</th>
          </tr>
        </ng-template>
        <ng-template #body let-b>
          <tr>
            <td>{{ b.warehouse_name }}</td>
            <td class="text-end">{{ +b.quantity | number:'1.2-2' }}</td>
            <td class="text-end">{{ b.available_quantity | number:'1.2-2' }}</td>
            <td class="text-end">{{ +b.average_cost | number:'1.2-2' }}</td>
            <td class="text-end">{{ +b.total_value | number:'1.2-2' }}</td>
          </tr>
        </ng-template>
        <ng-template #emptymessage>
          <tr><td colspan="5" class="text-center">{{ 'COMMON.NO_DATA' | translate }}</td></tr>
        </ng-template>
      </p-table>
    </div>

    <!-- Costing Section -->
    @if (productCost()) {
      <div class="section-card">
        <div class="section-header">
          <h3><i class="pi pi-calculator"></i> {{ 'INVENTORY.COSTING_INFO' | translate }}</h3>
        </div>
        <div class="costing-summary">
          <div class="cost-stat">
            <span class="cost-stat-label">{{ 'INVENTORY.COSTING_METHOD' | translate }}</span>
            <span class="cost-stat-value">
              <p-tag [value]="productCost()!.costing_method === 'fifo' ? 'FIFO' : 'Weighted Avg'" severity="info" />
            </span>
          </div>
          <div class="cost-stat">
            <span class="cost-stat-label">{{ 'INVENTORY.UNIT_COST' | translate }}</span>
            <span class="cost-stat-value mono">{{ productCost()!.unit_cost | number:'1.2-2' }}</span>
          </div>
          <div class="cost-stat">
            <span class="cost-stat-label">{{ 'INVENTORY.TOTAL_QUANTITY' | translate }}</span>
            <span class="cost-stat-value mono">{{ productCost()!.total_quantity | number:'1.0-2' }}</span>
          </div>
          <div class="cost-stat">
            <span class="cost-stat-label">{{ 'INVENTORY.TOTAL_VALUE' | translate }}</span>
            <span class="cost-stat-value mono fw-bold">{{ productCost()!.total_value | number:'1.2-2' }}</span>
          </div>
        </div>
      </div>
    }

    <!-- Cost Layers -->
    @if (costLayers().length > 0 || showExhausted()) {
      <div class="section-card">
        <div class="section-header">
          <h3><i class="pi pi-bars"></i> {{ 'INVENTORY.COST_LAYERS' | translate }}</h3>
          <div class="filter-controls">
            <label class="toggle-label">
              {{ 'INVENTORY.SHOW_EXHAUSTED' | translate }}
              <p-toggleswitch [ngModel]="showExhausted()" (ngModelChange)="toggleExhausted()" />
            </label>
          </div>
        </div>
        <p-table [value]="costLayers()" styleClass="p-datatable-sm p-datatable-gridlines"
          [paginator]="costLayers().length > 10" [rows]="10">
          <ng-template #header>
            <tr>
              <th>{{ 'INVENTORY.DATE' | translate }}</th>
              <th>{{ 'INVENTORY.WAREHOUSE' | translate }}</th>
              <th>{{ 'INVENTORY.REFERENCE_TYPE' | translate }}</th>
              <th class="text-end">{{ 'INVENTORY.ORIGINAL_QTY' | translate }}</th>
              <th class="text-end">{{ 'INVENTORY.REMAINING_QTY' | translate }}</th>
              <th class="text-end">{{ 'INVENTORY.UNIT_COST' | translate }}</th>
              <th class="text-end">{{ 'INVENTORY.REMAINING_VALUE' | translate }}</th>
            </tr>
          </ng-template>
          <ng-template #body let-layer>
            <tr [ngClass]="{'exhausted-row': +layer.remaining_quantity <= 0}">
              <td>{{ layer.date }}</td>
              <td>{{ layer.warehouse_name }}</td>
              <td>
                <p-tag [value]="layer.reference_type" [severity]="layer.reference_type.includes('receipt') ? 'success' : 'info'" />
              </td>
              <td class="text-end">{{ +layer.original_quantity | number:'1.2-2' }}</td>
              <td class="text-end" [ngClass]="{'text-danger': +layer.remaining_quantity <= 0, 'text-success': +layer.remaining_quantity > 0}">
                {{ +layer.remaining_quantity | number:'1.2-2' }}
              </td>
              <td class="text-end mono">{{ +layer.unit_cost | number:'1.2-2' }}</td>
              <td class="text-end mono fw-bold">{{ layer.total_remaining_value | number:'1.2-2' }}</td>
            </tr>
          </ng-template>
          <ng-template #emptymessage>
            <tr><td colspan="7" class="text-center">{{ 'COMMON.NO_DATA' | translate }}</td></tr>
          </ng-template>
        </p-table>
      </div>
    }

    <!-- Transactions Table -->
    <div class="section-card">
      <div class="section-header">
        <h3><i class="pi pi-list"></i> {{ 'INVENTORY.TRANSACTIONS' | translate }}</h3>
        <div class="filter-controls">
          <div class="date-presets">
            <p-button [label]="'INVENTORY.DATE_TODAY' | translate" [outlined]="activeDatePreset() !== 'today'"
              [severity]="activeDatePreset() === 'today' ? 'primary' : 'secondary'" size="small" (onClick)="setDatePreset('today')" />
            <p-button [label]="'INVENTORY.DATE_WEEK' | translate" [outlined]="activeDatePreset() !== 'week'"
              [severity]="activeDatePreset() === 'week' ? 'primary' : 'secondary'" size="small" (onClick)="setDatePreset('week')" />
            <p-button [label]="'INVENTORY.DATE_MONTH' | translate" [outlined]="activeDatePreset() !== 'month'"
              [severity]="activeDatePreset() === 'month' ? 'primary' : 'secondary'" size="small" (onClick)="setDatePreset('month')" />
            <p-button [label]="'INVENTORY.DATE_ALL' | translate" [outlined]="activeDatePreset() !== 'all'"
              [severity]="activeDatePreset() === 'all' ? 'primary' : 'secondary'" size="small" (onClick)="setDatePreset('all')" />
          </div>
          <div class="date-range-inputs">
            <p-datepicker [ngModel]="dateFrom()" (ngModelChange)="onDateFromChange($event)"
              [placeholder]="'INVENTORY.DATE_FROM' | translate" dateFormat="yy-mm-dd"
              [showIcon]="true" [style]="{width:'160px'}" [showClear]="true" />
            <p-datepicker [ngModel]="dateTo()" (ngModelChange)="onDateToChange($event)"
              [placeholder]="'INVENTORY.DATE_TO' | translate" dateFormat="yy-mm-dd"
              [showIcon]="true" [style]="{width:'160px'}" [showClear]="true" />
          </div>
          <p-select [options]="warehouses()" optionLabel="name" optionValue="id" [showClear]="true"
            [placeholder]="'INVENTORY.ALL_WAREHOUSES' | translate" [style]="{width:'180px'}"
            [ngModel]="selectedWarehouseId()" (onChange)="onWarehouseFilter($event.value)" />
        </div>
      </div>
      <p-table [value]="entries()" [paginator]="true" [rows]="25" [rowsPerPageOptions]="[25,50,100]"
        [scrollable]="true" scrollHeight="500px" styleClass="p-datatable-sm p-datatable-gridlines">
        <ng-template #header>
          <tr>
            <th>{{ 'INVENTORY.DATE' | translate }}</th>
            <th>{{ 'INVENTORY.MOVEMENT_TYPE' | translate }}</th>
            <th>{{ 'INVENTORY.WAREHOUSE' | translate }}</th>
            <th class="text-end">{{ 'INVENTORY.QTY_IN' | translate }}</th>
            <th class="text-end">{{ 'INVENTORY.QTY_OUT' | translate }}</th>
            <th class="text-end">{{ 'INVENTORY.BALANCE' | translate }}</th>
            <th class="text-end">{{ 'INVENTORY.UNIT_COST' | translate }}</th>
            <th>{{ 'INVENTORY.NOTES' | translate }}</th>
          </tr>
        </ng-template>
        <ng-template #body let-entry>
          <tr>
            <td>{{ entry.date }}</td>
            <td>
              <p-tag [value]="entry.movement_type_label" [severity]="getMovementSeverity(entry.movement_type)" />
            </td>
            <td>{{ entry.warehouse_name }}</td>
            <td class="text-end" [ngClass]="{'text-success': +entry.quantity_in > 0}">
              {{ +entry.quantity_in > 0 ? (+entry.quantity_in | number:'1.2-2') : '—' }}
            </td>
            <td class="text-end" [ngClass]="{'text-danger': +entry.quantity_out > 0}">
              {{ +entry.quantity_out > 0 ? (+entry.quantity_out | number:'1.2-2') : '—' }}
            </td>
            <td class="text-end mono">{{ +entry.balance_after | number:'1.2-2' }}</td>
            <td class="text-end">{{ +entry.unit_cost | number:'1.2-2' }}</td>
            <td>{{ entry.notes || '—' }}</td>
          </tr>
        </ng-template>
        <ng-template #emptymessage>
          <tr><td colspan="8" class="text-center">{{ 'COMMON.NO_DATA' | translate }}</td></tr>
        </ng-template>
      </p-table>
    </div>
  }
</div>
