<p-toast />
<p-confirmDialog />

<div class="requests-page">
  <app-page-header title="PURCHASES.PURCHASE_REQUESTS" subtitle="PURCHASES.TITLE" (refresh)="retry()">
    <p-button
      [label]="'PURCHASES.NEW_REQUEST' | translate"
      icon="pi pi-plus"
      (onClick)="openNew()"
    />
  </app-page-header>

  <ng-template #bodyTpl let-pr>
    <tr>
      <td class="mono">{{ pr.request_number }}</td>
      <td>{{ pr.date }}</td>
      <td>{{ pr.requested_by_name || '-' }}</td>
      <td>{{ pr.department || pr.department_ar || '-' }}</td>
      <td>
        <p-tag
          [value]="getPriorityLabel(pr.priority)"
          [severity]="getPrioritySeverity(pr.priority)"
        />
      </td>
      <td>{{ pr.needed_by || '-' }}</td>
      <td class="amount">{{ pr.subtotal | number:'1.2-2' }}</td>
      <td>
        <p-tag
          [value]="getStatusLabel(pr.status)"
          [severity]="getStatusSeverity(pr.status)"
        />
      </td>
      <td>
        <div class="action-buttons">
          <p-button
            icon="pi pi-eye"
            [rounded]="true"
            [text]="true"
            severity="info"
            (onClick)="viewRequest(pr)"
            [pTooltip]="'COMMON.VIEW' | translate"
          />
          @if (pr.status === 'draft') {
            <p-button
              icon="pi pi-pencil"
              [rounded]="true"
              [text]="true"
              severity="info"
              (onClick)="editRequest(pr)"
              [pTooltip]="'COMMON.EDIT' | translate"
            />
            <p-button
              icon="pi pi-send"
              [rounded]="true"
              [text]="true"
              severity="success"
              (onClick)="submitApproval(pr)"
              [pTooltip]="'PURCHASES.SUBMIT_APPROVAL' | translate"
            />
            <p-button
              icon="pi pi-trash"
              [rounded]="true"
              [text]="true"
              severity="danger"
              (onClick)="deleteRequest(pr)"
              [pTooltip]="'COMMON.DELETE' | translate"
            />
          }
          @if (pr.status === 'pending_approval') {
            <p-button
              icon="pi pi-check"
              [rounded]="true"
              [text]="true"
              severity="success"
              (onClick)="approveRequest(pr)"
              [pTooltip]="'PURCHASES.APPROVE' | translate"
            />
            <p-button
              icon="pi pi-times"
              [rounded]="true"
              [text]="true"
              severity="danger"
              (onClick)="rejectRequest(pr)"
              [pTooltip]="'PURCHASES.REJECT' | translate"
            />
          }
          @if (pr.status === 'approved') {
            <p-button
              icon="pi pi-arrow-right"
              [rounded]="true"
              [text]="true"
              severity="info"
              (onClick)="openConvertDialog(pr)"
              [pTooltip]="'PURCHASES.CONVERT_TO_ORDER' | translate"
            />
          }
          @if (pr.status !== 'cancelled' && pr.status !== 'converted') {
            <p-button
              icon="pi pi-ban"
              [rounded]="true"
              [text]="true"
              severity="danger"
              (onClick)="cancelRequest(pr)"
              [pTooltip]="'COMMON.CANCEL' | translate"
            />
          }
        </div>
      </td>
    </tr>
  </ng-template>

  <ng-template #filtersTpl>
    <app-sales-filter-bar
      [statusOptions]="statusOptions"
      [customers]="[]"
      (filtersChange)="onFiltersChange($event)"
    />
  </ng-template>

  <app-data-table
    [data]="tableData()"
    [lazy]="true"
    [totalRecords]="totalRecords()"
    [first]="first"
    [loading]="tableLoading()"
    [rows]="rows"
    (onLazyLoad)="onPageChange($event)"
    [columns]="columns"
    (retry)="retry()"
    [bodyTpl]="bodyTpl"
    [filtersTpl]="filtersTpl"
  >
  </app-data-table>
</div>

<!-- Create/Edit Dialog -->
<app-form-dialog
  [(visible)]="dialogVisible"
  [header]="editingRequest() ? ('PURCHASES.EDIT_REQUEST' | translate) : ('PURCHASES.NEW_REQUEST' | translate)"
  width="900px"
  [saving]="saving()"
  [showFooter]="false"
>
  <form [formGroup]="requestForm" class="request-form">
    <!-- Row 1: Date + Priority + Needed By + Cost Center -->
    <div class="form-grid">
      <div class="form-field">
        <label>{{ 'PURCHASES.DATE' | translate }} *</label>
        <p-datepicker formControlName="date" dateFormat="yy-mm-dd" [showIcon]="true" />
      </div>
      <div class="form-field">
        <label>{{ 'PURCHASES.PRIORITY' | translate }}</label>
        <p-select
          formControlName="priority"
          [options]="priorityOptions"
          optionLabel="label"
          optionValue="value"
          [style]="{ width: '100%' }"
          appendTo="body"
        />
      </div>
      <div class="form-field">
        <label>{{ 'PURCHASES.NEEDED_BY' | translate }}</label>
        <p-datepicker formControlName="needed_by" dateFormat="yy-mm-dd" [showIcon]="true" [showClear]="true" />
      </div>
      <div class="form-field">
        <label>{{ 'PURCHASES.COST_CENTER' | translate }}</label>
        <p-select
          formControlName="cost_center_id"
          [options]="(costCenters$ | async) || []"
          optionLabel="name"
          optionValue="id"
          [showClear]="true"
          [placeholder]="'PURCHASES.COST_CENTER' | translate"
          [style]="{ width: '100%' }"
          appendTo="body"
        />
      </div>
    </div>

    <!-- Row 2: Department + Department AR -->
    <div class="form-grid">
      <div class="form-field span-2">
        <label>{{ 'PURCHASES.DEPARTMENT' | translate }}</label>
        <input pInputText formControlName="department" />
      </div>
      <div class="form-field span-2">
        <label>{{ 'PURCHASES.DEPARTMENT_AR' | translate }}</label>
        <input pInputText formControlName="department_ar" />
      </div>
    </div>

    <!-- Row 3: Reason -->
    <div class="form-grid">
      <div class="form-field span-2">
        <label>{{ 'PURCHASES.REASON' | translate }} *</label>
        <textarea pTextarea formControlName="reason" rows="2"></textarea>
      </div>
      <div class="form-field span-2">
        <label>{{ 'PURCHASES.REASON_AR' | translate }}</label>
        <textarea pTextarea formControlName="reason_ar" rows="2"></textarea>
      </div>
    </div>

    <!-- Line Items Section (simplified) -->
    <div class="lines-section">
      <div class="lines-header">
        <h3>{{ 'PURCHASES.LINE_ITEMS' | translate }}</h3>
        <p-button
          icon="pi pi-plus"
          [label]="'PURCHASES.ADD_LINE' | translate"
          severity="secondary"
          [outlined]="true"
          size="small"
          (onClick)="addItem()"
        />
      </div>

      <table class="lines-table">
        <thead>
          <tr>
            <th class="col-product">{{ 'PURCHASES.PRODUCT' | translate }}</th>
            <th class="col-unit">{{ 'PURCHASES.UNIT' | translate }}</th>
            <th class="col-qty">{{ 'PURCHASES.QUANTITY' | translate }}</th>
            <th class="col-price">{{ 'PURCHASES.EST_PRICE' | translate }}</th>
            <th class="col-supplier">{{ 'PURCHASES.PREFERRED_SUPPLIER' | translate }}</th>
            <th class="col-total">{{ 'PURCHASES.EST_TOTAL' | translate }}</th>
            <th class="col-action"></th>
          </tr>
        </thead>
        <tbody formArrayName="items">
          @for (item of items.controls; track item; let i = $index) {
            <tr [formGroupName]="i">
              <td>
                <p-select
                  formControlName="product_id"
                  [options]="searchedProducts()"
                  optionValue="id"
                  [filter]="true"
                  [filterBy]="'name_ar,name_en,code,barcode'"
                  (onFilter)="onProductSearch($event)"
                  appendTo="body"
                  [style]="{ width: '100%' }"
                  [placeholder]="'PURCHASES.PRODUCT' | translate"
                  [loading]="searchLoading()">
                  <ng-template #item let-product>
                    <div style="display: flex; flex-direction: column; gap: 1px;">
                      <small style="color: #94a3b8;">{{ product.category?.name_ar || '—' }}</small>
                      <span>{{ product.name_ar }} <small style="color: #64748b;">({{ product.code }})</small></span>
                    </div>
                  </ng-template>
                  <ng-template #selectedItem let-product>
                    <span>{{ product.name_ar }}</span>
                  </ng-template>
                </p-select>
              </td>
              <td>
                <p-select
                  formControlName="unit_id"
                  [options]="(units$ | async) || []"
                  optionLabel="name"
                  optionValue="id"
                  [placeholder]="'PURCHASES.UNIT' | translate"
                  [style]="{ width: '100%' }"
                  appendTo="body"
                />
              </td>
              <td>
                <p-inputNumber formControlName="quantity" [min]="0.01" mode="decimal" [minFractionDigits]="0" [maxFractionDigits]="4" [style]="{ width: '100%' }" />
              </td>
              <td>
                <p-inputNumber formControlName="estimated_price" [min]="0" mode="decimal" [minFractionDigits]="2" [maxFractionDigits]="4" [style]="{ width: '100%' }" />
              </td>
              <td>
                <p-select
                  formControlName="preferred_supplier_id"
                  [options]="searchedSuppliers()"
                  optionValue="id"
                  [filter]="true"
                  [filterBy]="'name,name_ar,name_en,code'"
                  (onFilter)="onSupplierSearch($event)"
                  [showClear]="true"
                  appendTo="body"
                  [style]="{ width: '100%' }"
                  [placeholder]="'PURCHASES.SUPPLIER' | translate"
                  [loading]="supplierSearchLoading()">
                  <ng-template #item let-partner>
                    <span>{{ partner.code }} - {{ partner.name }}</span>
                  </ng-template>
                  <ng-template #selectedItem let-partner>
                    <span>{{ partner.name }}</span>
                  </ng-template>
                </p-select>
              </td>
              <td class="amount line-total-cell">
                {{ getLineTotal(i) | number:'1.2-2' }}
              </td>
              <td>
                <p-button
                  icon="pi pi-times"
                  [rounded]="true"
                  [text]="true"
                  severity="danger"
                  (onClick)="removeItem(i)"
                  [disabled]="items.length <= 1"
                  size="small"
                />
              </td>
            </tr>
          }
        </tbody>
      </table>

      @if (items.length === 0) {
        <div class="no-items">{{ 'PURCHASES.NO_ITEMS' | translate }}</div>
      }
    </div>

    <!-- Totals Section -->
    <div class="totals-section">
      <div class="totals-row grand-total">
        <span class="totals-label">{{ 'PURCHASES.EST_TOTAL' | translate }}</span>
        <span class="totals-value">{{ estimatedTotal | number:'1.2-2' }}</span>
      </div>
    </div>

    <!-- Notes -->
    <div class="form-grid">
      <div class="form-field span-2">
        <label>{{ 'PURCHASES.NOTES' | translate }}</label>
        <textarea pTextarea formControlName="notes" rows="2"></textarea>
      </div>
      <div class="form-field span-2">
        <label>{{ 'PURCHASES.NOTES_AR' | translate }}</label>
        <textarea pTextarea formControlName="notes_ar" rows="2"></textarea>
      </div>
    </div>
  </form>
  <div class="dialog-custom-footer">
    <p-button
      [label]="'COMMON.CANCEL' | translate"
      icon="pi pi-times"
      severity="secondary"
      (onClick)="dialogVisible.set(false)"
    />
    <p-button
      [label]="'COMMON.SAVE' | translate"
      icon="pi pi-check"
      (onClick)="onSave()"
      [loading]="saving()"
      [disabled]="items.length < 1"
    />
  </div>
</app-form-dialog>

<!-- View Dialog -->
<p-dialog
  [header]="'PURCHASES.PURCHASE_REQUEST' | translate"
  [(visible)]="viewDialogVisible"
  [modal]="true"
  [style]="{ width: '800px' }"
  [closable]="true"
>
  @if (viewingRequest(); as pr) {
    <div class="view-request">
      <div class="view-header-info">
        <div class="info-item">
          <label>{{ 'PURCHASES.REQUEST_NUMBER' | translate }}</label>
          <span class="mono">{{ pr.request_number }}</span>
        </div>
        <div class="info-item">
          <label>{{ 'PURCHASES.DATE' | translate }}</label>
          <span>{{ pr.date }}</span>
        </div>
        <div class="info-item">
          <label>{{ 'PURCHASES.STATUS' | translate }}</label>
          <p-tag [value]="getStatusLabel(pr.status)" [severity]="getStatusSeverity(pr.status)" />
        </div>
        <div class="info-item">
          <label>{{ 'PURCHASES.PRIORITY' | translate }}</label>
          <p-tag [value]="getPriorityLabel(pr.priority)" [severity]="getPrioritySeverity(pr.priority)" />
        </div>
        @if (pr.requested_by_name) {
          <div class="info-item">
            <label>{{ 'PURCHASES.REQUESTED_BY' | translate }}</label>
            <span>{{ pr.requested_by_name }}</span>
          </div>
        }
        @if (pr.department || pr.department_ar) {
          <div class="info-item">
            <label>{{ 'PURCHASES.DEPARTMENT' | translate }}</label>
            <span>{{ pr.department || pr.department_ar }}</span>
          </div>
        }
        @if (pr.needed_by) {
          <div class="info-item">
            <label>{{ 'PURCHASES.NEEDED_BY' | translate }}</label>
            <span>{{ pr.needed_by }}</span>
          </div>
        }
      </div>

      @if (pr.reason || pr.reason_ar) {
        <div class="view-description">
          @if (pr.reason) {
            <label>{{ 'PURCHASES.REASON' | translate }}</label>
            <p>{{ pr.reason }}</p>
          }
          @if (pr.reason_ar) {
            <label>{{ 'PURCHASES.REASON_AR' | translate }}</label>
            <p>{{ pr.reason_ar }}</p>
          }
        </div>
      }

      <table class="view-lines-table">
        <thead>
          <tr>
            <th>#</th>
            <th>{{ 'PURCHASES.PRODUCT' | translate }}</th>
            <th>{{ 'PURCHASES.UNIT' | translate }}</th>
            <th>{{ 'PURCHASES.QUANTITY' | translate }}</th>
            <th>{{ 'PURCHASES.EST_PRICE' | translate }}</th>
            <th>{{ 'PURCHASES.PREFERRED_SUPPLIER' | translate }}</th>
            <th>{{ 'PURCHASES.EST_TOTAL' | translate }}</th>
          </tr>
        </thead>
        <tbody>
          @for (item of pr.items; track $index) {
            <tr>
              <td>{{ $index + 1 }}</td>
              <td>{{ item.product_name }}</td>
              <td>{{ item.unit_name }}</td>
              <td class="amount">{{ item.quantity }}</td>
              <td class="amount">{{ item.estimated_price | number:'1.2-2' }}</td>
              <td>{{ item.preferred_supplier_name || '-' }}</td>
              <td class="amount">{{ item.estimated_total | number:'1.2-2' }}</td>
            </tr>
          }
        </tbody>
        <tfoot>
          <tr class="grand-total-row">
            <td colspan="5"></td>
            <td><strong>{{ 'PURCHASES.EST_TOTAL' | translate }}</strong></td>
            <td class="amount"><strong>{{ pr.subtotal | number:'1.2-2' }}</strong></td>
          </tr>
        </tfoot>
      </table>

      <!-- Approval Timeline -->
      @if (pr.approved_by_name || pr.created_by_name) {
        <div class="approval-timeline">
          <h4>{{ 'PURCHASES.TIMELINE' | translate }}</h4>
          @if (pr.created_by_name) {
            <div class="timeline-item">
              <i class="pi pi-file"></i>
              <span>{{ 'PURCHASES.CREATED_BY' | translate }}: {{ pr.created_by_name }} ({{ pr.created_at }})</span>
            </div>
          }
          @if (pr.approved_by_name) {
            <div class="timeline-item">
              <i class="pi pi-check-circle"></i>
              <span>{{ 'PURCHASES.APPROVED_BY' | translate }}: {{ pr.approved_by_name }} ({{ pr.approved_at }})</span>
            </div>
          }
        </div>
      }

      @if (pr.notes || pr.notes_ar) {
        <div class="view-description">
          @if (pr.notes) {
            <label>{{ 'PURCHASES.NOTES' | translate }}</label>
            <p>{{ pr.notes }}</p>
          }
          @if (pr.notes_ar) {
            <label>{{ 'PURCHASES.NOTES_AR' | translate }}</label>
            <p>{{ pr.notes_ar }}</p>
          }
        </div>
      }
    </div>
  }
  <ng-template #footer>
    <p-button
      [label]="'COMMON.CLOSE' | translate"
      icon="pi pi-times"
      severity="secondary"
      (onClick)="viewDialogVisible.set(false)"
    />
  </ng-template>
</p-dialog>

<!-- Convert to PO Dialog -->
<p-dialog
  [header]="'PURCHASES.CONVERT_TO_ORDER' | translate"
  [(visible)]="convertDialogVisible"
  [modal]="true"
  [style]="{ width: '450px' }"
  [closable]="true"
>
  <div style="display: flex; flex-direction: column; gap: 1rem;">
    <div>
      <label style="display: block; margin-bottom: 4px; font-size: 0.85rem; font-weight: 600;">{{ 'PURCHASES.SELECT_SUPPLIER' | translate }} *</label>
      <p-select
        [ngModel]="convertSupplierId()"
        (ngModelChange)="convertSupplierId.set($event)"
        [ngModelOptions]="{standalone: true}"
        [options]="searchedSuppliers()"
        optionValue="id"
        [filter]="true"
        [filterBy]="'name,name_ar,name_en,code'"
        (onFilter)="onSupplierSearch($event)"
        [placeholder]="'PURCHASES.SUPPLIER' | translate"
        [style]="{ width: '100%' }"
        appendTo="body"
        [loading]="supplierSearchLoading()"
      >
        <ng-template #item let-partner>
          <span>{{ partner.code }} - {{ partner.name }}</span>
        </ng-template>
        <ng-template #selectedItem let-partner>
          <span>{{ partner.code }} - {{ partner.name }}</span>
        </ng-template>
      </p-select>
    </div>
  </div>
  <ng-template #footer>
    <p-button
      [label]="'COMMON.CANCEL' | translate"
      icon="pi pi-times"
      severity="secondary"
      (onClick)="convertDialogVisible.set(false)"
    />
    <p-button
      [label]="'PURCHASES.CONVERT_TO_ORDER' | translate"
      icon="pi pi-arrow-right"
      (onClick)="confirmConvertToOrder()"
      [loading]="saving()"
      [disabled]="!convertSupplierId()"
    />
  </ng-template>
</p-dialog>
