<app-page-header
  [title]="'POS.SETTINGS' | translate"
  [subtitle]="'POS.TERMINALS' | translate"
  icon="pi pi-cog"
/>

<p-tabs [value]="activeTab" (valueChange)="onTabChange($event)">
  <p-tablist>
    <p-tab value="terminals">
      <i class="pi pi-desktop me-2"></i>{{ 'POS.TERMINALS' | translate }}
    </p-tab>
    <p-tab value="coupons">
      <i class="pi pi-ticket me-2"></i>{{ 'POS.COUPONS' | translate }}
    </p-tab>
  </p-tablist>

  <p-tabpanels>
    <!-- ═══ Terminals Tab ═══ -->
    <p-tabpanel value="terminals">
      <div class="flex justify-between items-center mb-4 mt-2">
        <h3 class="m-0 text-lg font-bold">{{ 'POS.TERMINALS' | translate }}</h3>
        <button pButton [label]="'COMMON.CREATE' | translate" icon="pi pi-plus" (click)="openNewTerminal()"></button>
      </div>

      @if (terminalsLoading()) {
        <div class="text-center py-8"><i class="pi pi-spin pi-spinner text-3xl text-text-muted"></i></div>
      } @else if (terminals().length === 0) {
        <div class="text-center py-8 text-text-muted">{{ 'COMMON.NO_DATA' | translate }}</div>
      } @else {
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          @for (t of terminals(); track t.id) {
            <div class="bg-white rounded-xl border border-surface-border p-4 shadow-sm hover:shadow-md transition-shadow">
              <div class="flex items-start justify-between mb-3">
                <div>
                  <h4 class="m-0 font-bold text-base">{{ t.name_ar || t.name }}</h4>
                  <span class="text-sm text-text-muted">{{ t.code }}</span>
                </div>
                <p-tag [value]="t.is_active ? ('COMMON.ACTIVE' | translate) : ('COMMON.INACTIVE' | translate)"
                       [severity]="t.is_active ? 'success' : 'danger'" />
              </div>
              <div class="flex flex-col gap-1 text-sm mb-3">
                <div class="flex items-center gap-2">
                  <i class="pi pi-building text-text-muted"></i>
                  <span>{{ t.branch?.name }}</span>
                </div>
                <div class="flex items-center gap-2">
                  <i class="pi pi-warehouse text-text-muted"></i>
                  <span>{{ t.warehouse?.name }}</span>
                </div>
                @if (getAccountName(t.id)) {
                  <div class="flex items-center gap-2">
                    <i class="pi pi-wallet text-text-muted"></i>
                    <span>{{ getAccountName(t.id) }}</span>
                  </div>
                }
              </div>
              <div class="flex flex-wrap gap-1 mb-3">
                @if (t.settings?.allow_discount) {
                  <span class="text-xs bg-green-50 text-green-700 px-2 py-0.5 rounded-full">{{ 'POS.ALLOW_DISCOUNT' | translate }}</span>
                }
                @if (t.settings?.allow_price_override) {
                  <span class="text-xs bg-blue-50 text-blue-700 px-2 py-0.5 rounded-full">{{ 'POS.ALLOW_PRICE_OVERRIDE' | translate }}</span>
                }
                @if (t.settings?.require_customer) {
                  <span class="text-xs bg-amber-50 text-amber-700 px-2 py-0.5 rounded-full">{{ 'POS.REQUIRE_CUSTOMER' | translate }}</span>
                }
                @if (t.settings?.allow_negative_stock) {
                  <span class="text-xs bg-red-50 text-red-700 px-2 py-0.5 rounded-full">{{ 'POS.ALLOW_NEGATIVE_STOCK' | translate }}</span>
                }
              </div>
              <div class="flex gap-2">
                <button pButton icon="pi pi-pencil" [label]="'COMMON.EDIT' | translate" severity="secondary" size="small" (click)="editTerminal(t)"></button>
                <button pButton icon="pi pi-trash" severity="danger" size="small" [pTooltip]="'COMMON.DELETE' | translate" (click)="deleteTerminal(t)"></button>
              </div>
            </div>
          }
        </div>
      }
    </p-tabpanel>

    <!-- ═══ Coupons Tab ═══ -->
    <p-tabpanel value="coupons">
      <div class="flex justify-between items-center mb-4 mt-2">
        <h3 class="m-0 text-lg font-bold">{{ 'POS.COUPONS' | translate }}</h3>
        <button pButton [label]="'COMMON.CREATE' | translate" icon="pi pi-plus" (click)="openNewCoupon()"></button>
      </div>

      @if (couponsLoading()) {
        <div class="text-center py-8"><i class="pi pi-spin pi-spinner text-3xl text-text-muted"></i></div>
      } @else if (coupons().length === 0) {
        <div class="text-center py-8 text-text-muted">{{ 'COMMON.NO_DATA' | translate }}</div>
      } @else {
        <div class="overflow-x-auto">
          <table class="w-full text-sm">
            <thead>
              <tr class="border-b border-surface-border text-text-muted text-start">
                <th class="py-3 px-3 font-semibold">{{ 'POS.COUPON_CODE' | translate }}</th>
                <th class="py-3 px-3 font-semibold">{{ 'POS.TYPE' | translate }}</th>
                <th class="py-3 px-3 font-semibold">{{ 'POS.VALUE' | translate }}</th>
                <th class="py-3 px-3 font-semibold">{{ 'POS.VALID_FROM' | translate }}</th>
                <th class="py-3 px-3 font-semibold">{{ 'POS.VALID_TO' | translate }}</th>
                <th class="py-3 px-3 font-semibold">{{ 'POS.USAGE' | translate }}</th>
                <th class="py-3 px-3 font-semibold">{{ 'COMMON.STATUS' | translate }}</th>
                <th class="py-3 px-3 font-semibold"></th>
              </tr>
            </thead>
            <tbody>
              @for (c of coupons(); track c.id) {
                <tr class="border-b border-surface-border hover:bg-surface-hover transition-colors">
                  <td class="py-3 px-3 font-mono font-bold">{{ c.code }}</td>
                  <td class="py-3 px-3">
                    <p-tag [value]="c.type === 'percentage' ? '%' : ('POS.FIXED' | translate)" [severity]="c.type === 'percentage' ? 'info' : 'warn'" />
                  </td>
                  <td class="py-3 px-3">{{ c.value }}{{ c.type === 'percentage' ? '%' : '' }}</td>
                  <td class="py-3 px-3">{{ c.valid_from | date:'shortDate' }}</td>
                  <td class="py-3 px-3">{{ c.valid_to | date:'shortDate' }}</td>
                  <td class="py-3 px-3">{{ c.usage_count || 0 }}{{ c.usage_limit ? ' / ' + c.usage_limit : '' }}</td>
                  <td class="py-3 px-3">
                    <p-tag [value]="c.is_active ? ('COMMON.ACTIVE' | translate) : ('COMMON.INACTIVE' | translate)"
                           [severity]="c.is_active ? 'success' : 'danger'" />
                  </td>
                  <td class="py-3 px-3">
                    <div class="flex gap-1">
                      <button pButton icon="pi pi-pencil" severity="secondary" size="small" [rounded]="true" [text]="true" (click)="editCoupon(c)"></button>
                      <button pButton icon="pi pi-trash" severity="danger" size="small" [rounded]="true" [text]="true" (click)="deleteCoupon(c)"></button>
                    </div>
                  </td>
                </tr>
              }
            </tbody>
          </table>
        </div>
      }
    </p-tabpanel>
  </p-tabpanels>
</p-tabs>

<!-- ═══ Terminal Dialog ═══ -->
<p-dialog
  [visible]="showTerminalDialog()"
  (visibleChange)="showTerminalDialog.set($event)"
  [header]="(editingTerminal() ? 'COMMON.EDIT' : 'COMMON.CREATE') | translate"
  [style]="{width: '600px'}"
  [modal]="true"
  [closable]="true"
>
  <div class="flex flex-col gap-4">
    <div class="grid grid-cols-2 gap-4">
      <div class="flex flex-col gap-1">
        <label class="font-semibold text-sm">{{ 'POS.TERMINAL_NAME' | translate }} *</label>
        <input pInputText [(ngModel)]="terminalForm.name" />
      </div>
      <div class="flex flex-col gap-1">
        <label class="font-semibold text-sm">{{ 'POS.TERMINAL_NAME_AR' | translate }}</label>
        <input pInputText [(ngModel)]="terminalForm.name_ar" />
      </div>
    </div>

    <div class="flex flex-col gap-1">
      <label class="font-semibold text-sm">{{ 'POS.TERMINAL_CODE' | translate }}</label>
      <input pInputText [(ngModel)]="terminalForm.code" />
    </div>

    <div class="grid grid-cols-2 gap-4">
      <div class="flex flex-col gap-1">
        <label class="font-semibold text-sm">{{ 'POS.BRANCH' | translate }} *</label>
        <p-select [options]="branches()" optionLabel="name" optionValue="id"
                  [(ngModel)]="terminalForm.branch_id" [placeholder]="'COMMON.SELECT' | translate"
                  [style]="{width: '100%'}" />
      </div>
      <div class="flex flex-col gap-1">
        <label class="font-semibold text-sm">{{ 'POS.WAREHOUSE' | translate }} *</label>
        <p-select [options]="warehouses()" optionLabel="name" optionValue="id"
                  [(ngModel)]="terminalForm.warehouse_id" [placeholder]="'COMMON.SELECT' | translate"
                  [style]="{width: '100%'}" />
      </div>
    </div>

    <div class="flex flex-col gap-1">
      <label class="font-semibold text-sm">{{ 'POS.RECEIVING_ACCOUNT' | translate }} *</label>
      <p-select [options]="bankAccounts()" optionLabel="bank_name" optionValue="id"
                [(ngModel)]="terminalForm.receiving_account_id" [placeholder]="'COMMON.SELECT' | translate"
                [style]="{width: '100%'}" />
    </div>

    <div class="flex items-center gap-3">
      <p-toggleSwitch [(ngModel)]="terminalForm.is_active" />
      <label class="font-semibold text-sm">{{ 'COMMON.ACTIVE' | translate }}</label>
    </div>

    <hr class="border-surface-border" />
    <h4 class="m-0 font-bold">{{ 'POS.TERMINAL_SETTINGS' | translate }}</h4>

    <div class="grid grid-cols-2 gap-3">
      <div class="flex items-center gap-3">
        <p-toggleSwitch [(ngModel)]="terminalForm.allow_discount" />
        <label class="text-sm">{{ 'POS.ALLOW_DISCOUNT' | translate }}</label>
      </div>
      <div class="flex items-center gap-3">
        <p-toggleSwitch [(ngModel)]="terminalForm.allow_price_override" />
        <label class="text-sm">{{ 'POS.ALLOW_PRICE_OVERRIDE' | translate }}</label>
      </div>
      <div class="flex items-center gap-3">
        <p-toggleSwitch [(ngModel)]="terminalForm.require_customer" />
        <label class="text-sm">{{ 'POS.REQUIRE_CUSTOMER' | translate }}</label>
      </div>
      <div class="flex items-center gap-3">
        <p-toggleSwitch [(ngModel)]="terminalForm.allow_negative_stock" />
        <label class="text-sm">{{ 'POS.ALLOW_NEGATIVE_STOCK' | translate }}</label>
      </div>
    </div>

    <div class="flex flex-col gap-1">
      <label class="font-semibold text-sm">{{ 'POS.RECEIPT_HEADER' | translate }}</label>
      <textarea pTextarea [(ngModel)]="terminalForm.receipt_header" rows="2"></textarea>
    </div>

    <div class="flex flex-col gap-1">
      <label class="font-semibold text-sm">{{ 'POS.RECEIPT_FOOTER' | translate }}</label>
      <textarea pTextarea [(ngModel)]="terminalForm.receipt_footer" rows="2"></textarea>
    </div>
  </div>

  <ng-template pTemplate="footer">
    <button pButton [label]="'COMMON.CANCEL' | translate" severity="secondary" (click)="showTerminalDialog.set(false)"></button>
    <button pButton [label]="'COMMON.SAVE' | translate" icon="pi pi-check" [loading]="terminalSaving()" (click)="saveTerminal()"></button>
  </ng-template>
</p-dialog>

<!-- ═══ Coupon Dialog ═══ -->
<p-dialog
  [visible]="showCouponDialog()"
  (visibleChange)="showCouponDialog.set($event)"
  [header]="(editingCoupon() ? 'COMMON.EDIT' : 'COMMON.CREATE') | translate"
  [style]="{width: '500px'}"
  [modal]="true"
  [closable]="true"
>
  <div class="flex flex-col gap-4">
    <div class="flex flex-col gap-1">
      <label class="font-semibold text-sm">{{ 'POS.COUPON_CODE' | translate }} *</label>
      <input pInputText [(ngModel)]="couponForm.code" class="font-mono" />
    </div>

    <div class="grid grid-cols-2 gap-4">
      <div class="flex flex-col gap-1">
        <label class="font-semibold text-sm">{{ 'POS.TYPE' | translate }} *</label>
        <p-select [options]="couponTypes" optionValue="value"
                  [(ngModel)]="couponForm.type" [style]="{width: '100%'}">
          <ng-template pTemplate="selectedItem" let-item>{{ item.label | translate }}</ng-template>
          <ng-template pTemplate="item" let-item>{{ item.label | translate }}</ng-template>
        </p-select>
      </div>
      <div class="flex flex-col gap-1">
        <label class="font-semibold text-sm">{{ 'POS.VALUE' | translate }} *</label>
        <p-inputNumber [(ngModel)]="couponForm.value" [min]="0" [maxFractionDigits]="2" [style]="{width: '100%'}" />
      </div>
    </div>

    <div class="grid grid-cols-2 gap-4">
      <div class="flex flex-col gap-1">
        <label class="font-semibold text-sm">{{ 'POS.VALID_FROM' | translate }} *</label>
        <p-datepicker [(ngModel)]="couponForm.valid_from" dateFormat="yy-mm-dd" [style]="{width: '100%'}" />
      </div>
      <div class="flex flex-col gap-1">
        <label class="font-semibold text-sm">{{ 'POS.VALID_TO' | translate }} *</label>
        <p-datepicker [(ngModel)]="couponForm.valid_to" dateFormat="yy-mm-dd" [style]="{width: '100%'}" />
      </div>
    </div>

    <div class="grid grid-cols-2 gap-4">
      <div class="flex flex-col gap-1">
        <label class="font-semibold text-sm">{{ 'POS.MAX_DISCOUNT' | translate }}</label>
        <p-inputNumber [(ngModel)]="couponForm.max_discount" [min]="0" [maxFractionDigits]="2" [style]="{width: '100%'}" />
      </div>
      <div class="flex flex-col gap-1">
        <label class="font-semibold text-sm">{{ 'POS.MIN_ORDER_AMOUNT' | translate }}</label>
        <p-inputNumber [(ngModel)]="couponForm.min_order_amount" [min]="0" [maxFractionDigits]="2" [style]="{width: '100%'}" />
      </div>
    </div>

    <div class="flex flex-col gap-1">
      <label class="font-semibold text-sm">{{ 'POS.USAGE_LIMIT' | translate }}</label>
      <p-inputNumber [(ngModel)]="couponForm.usage_limit" [min]="0" [style]="{width: '100%'}" />
    </div>

    <div class="flex items-center gap-3">
      <p-toggleSwitch [(ngModel)]="couponForm.is_active" />
      <label class="font-semibold text-sm">{{ 'COMMON.ACTIVE' | translate }}</label>
    </div>
  </div>

  <ng-template pTemplate="footer">
    <button pButton [label]="'COMMON.CANCEL' | translate" severity="secondary" (click)="showCouponDialog.set(false)"></button>
    <button pButton [label]="'COMMON.SAVE' | translate" icon="pi pi-check" [loading]="couponSaving()" (click)="saveCoupon()"></button>
  </ng-template>
</p-dialog>

<p-toast position="top-center" />
<p-confirmDialog />
