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

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

  <ng-template #filtersTpl>
      <!-- Filter Bar -->
      <div class="filter-bar" style="display: flex; gap: 0.75rem; flex-wrap: wrap; margin-bottom: 1rem; align-items: center; padding: 0.75rem 1rem;">
        <p-select
          [options]="[{label: ('COMMON.ALL' | translate), value: null}].concat(typeOptions)"
          [(ngModel)]="activeTypeFilter"
          optionLabel="label"
          optionValue="value"
          [placeholder]="'PARTNERS.TYPE' | translate"
          [style]="{'min-width': '140px'}"
        />
        <p-select
          [options]="[{label: ('COMMON.ALL' | translate), value: null}, {label: ('COMMON.ACTIVE' | translate), value: 'active'}, {label: ('PARTNERS.STATUS_FROZEN' | translate), value: 'frozen'}, {label: ('PARTNERS.STATUS_SUSPENDED' | translate), value: 'suspended'}]"
          [(ngModel)]="activeStatusFilter"
          optionLabel="label"
          optionValue="value"
          [placeholder]="'COMMON.STATUS' | translate"
          [style]="{'min-width': '140px'}"
        />
        <p-select
          [options]="[{label: ('COMMON.ALL' | translate), value: null}].concat(classificationOptions)"
          [(ngModel)]="activeClassFilter"
          optionLabel="label"
          optionValue="value"
          [placeholder]="'PARTNERS.CLASSIFICATION' | translate"
          [style]="{'min-width': '140px'}"
        />
        <p-select
          [options]="roleFilterOptions"
          [(ngModel)]="activeRoleFilter"
          optionLabel="label"
          optionValue="value"
          [placeholder]="'PARTNERS.ROLE' | translate"
          [style]="{'min-width': '140px'}"
        />
      </div>
    </ng-template>
    <ng-template #bodyTpl let-partner>
      <tr>
        <td class="mono">{{ partner.code }}</td>
        <td>{{ partner.name_ar }}</td>
        <td>
          <p-tag
            [value]="partner.type_label || partner.type"
            [severity]="partner.type === 'company' ? 'info' : 'secondary'"
          />
        </td>
        <td>
          @if (partner.is_customer && partner.is_supplier) {
            <span class="role-badges">
              <p-tag value="{{ 'PARTNERS.CUSTOMER' | translate }}" severity="success" />
              <p-tag value="{{ 'PARTNERS.SUPPLIER' | translate }}" severity="warn" />
            </span>
          } @else if (partner.is_customer) {
            <p-tag value="{{ 'PARTNERS.CUSTOMER' | translate }}" severity="success" />
          } @else if (partner.is_supplier) {
            <p-tag value="{{ 'PARTNERS.SUPPLIER' | translate }}" severity="warn" />
          }
        </td>
        <td class="amount" [class.text-danger]="getPartnerBalance(partner) < 0">
          @if (partner.ar_account_id || partner.ap_account_id) {
            {{ getPartnerBalance(partner) | number:'1.2-2' }}
          } @else {
            —
          }
        </td>
        <td>{{ partner.phone || '—' }}</td>
        <td>
          <p-tag
            [value]="partner.status_label || partner.status || '—'"
            [severity]="partner.status === 'active' ? 'success' : 'danger'"
          />
        </td>
        <td>
          <div class="action-buttons">
            <p-button
              icon="pi pi-pencil"
              [rounded]="true"
              [text]="true"
              severity="info"
              (onClick)="editPartner(partner)"
            />
            <p-button
              icon="pi pi-trash"
              [rounded]="true"
              [text]="true"
              severity="danger"
              (onClick)="deletePartner(partner)"
            />
            <p-button
              icon="pi pi-lock"
              [rounded]="true"
              [text]="true"
              severity="warn"
              (onClick)="freezePartner(partner)"
            />
            <p-button
              icon="pi pi-lock-open"
              [rounded]="true"
              [text]="true"
              severity="success"
              (onClick)="unfreezePartner(partner)"
            />
            <p-button
              icon="pi pi-wallet"
              [rounded]="true"
              [text]="true"
              severity="info"
              (onClick)="openDebtChanges(partner)"
            />
          </div>
        </td>
      </tr>
    </ng-template>
  <app-data-table
    [data]="filteredPartners"
    [loading]="tableLoading()"
    [columns]="columns"
    [lazy]="true"
    [totalRecords]="totalRecords()"
    [first]="first"
    [rows]="rows"
    [globalFilterFields]="['code', 'name_ar', 'name_en', 'email', 'phone']"
    (onLazyLoad)="onPageChange($event)"
    (retry)="retry()"
    [bodyTpl]="bodyTpl"
    [filtersTpl]="filtersTpl"
  >
  </app-data-table>
</div>

<!-- Create/Edit Dialog -->
<app-form-dialog
  [(visible)]="dialogVisible"
  [header]="editingPartner() ? ('PARTNERS.EDIT_PARTNER' | translate) : ('PARTNERS.NEW_PARTNER' | translate)"
  [saving]="savingPartner()"
  [width]="'850px'"
  (save)="onSave()"
>
  <form [formGroup]="partnerForm" class="dialog-form">
    <!-- Basic Info -->
    <h4 class="section-title">{{ 'PARTNERS.BASIC_INFO' | translate }}</h4>
    <div class="form-row">
      <div class="form-field">
        <label>{{ 'PARTNERS.CODE' | translate }}</label>
        <input pInputText formControlName="code" [placeholder]="'COMMON.AUTO_GENERATED' | translate" />
      </div>
      <div class="form-field">
        <label>{{ 'PARTNERS.TYPE' | translate }} *</label>
        <p-select formControlName="type" [options]="typeOptions" optionLabel="label" optionValue="value" />
      </div>
    </div>
    <div class="form-row">
      <div class="form-field">
        <label>{{ 'PARTNERS.NAME_AR' | translate }} *</label>
        <input pInputText formControlName="name_ar" />
        @if (partnerForm.get('name_ar')?.touched && partnerForm.get('name_ar')?.hasError('required')) {
          <small class="p-error">{{ 'COMMON.REQUIRED' | translate }}</small>
        }
      </div>
      <div class="form-field">
        <label>{{ 'PARTNERS.NAME_EN' | translate }}</label>
        <input pInputText formControlName="name_en" />
      </div>
    </div>
    <div class="form-row">
      <div class="form-field">
        <label>{{ 'PARTNERS.CATEGORY' | translate }}</label>
        <p-select
          formControlName="partner_category_id"
          [options]="(categories$ | async) || []"
          optionLabel="name"
          optionValue="id"
          [filter]="true"
          filterBy="name,name_ar,name_en"
          [showClear]="true"
          [placeholder]="'PARTNERS.SELECT_CATEGORY' | translate"
        />
      </div>
      <div class="form-field">
        <label>{{ 'PARTNERS.CLASSIFICATION' | translate }}</label>
        <p-select formControlName="classification" [options]="classificationOptions" optionLabel="label" optionValue="value" />
      </div>
    </div>
    <div class="form-row">
      <div class="form-field">
        <label>{{ 'COMMON.STATUS' | translate }}</label>
        <p-select formControlName="status" [options]="statusOptions" optionLabel="label" optionValue="value" />
      </div>
      <div class="form-field switch-row">
        <div class="switch-item">
          <p-toggleSwitch formControlName="is_customer" />
          <label>{{ 'PARTNERS.CUSTOMER' | translate }}</label>
        </div>
        <div class="switch-item">
          <p-toggleSwitch formControlName="is_supplier" />
          <label>{{ 'PARTNERS.SUPPLIER' | translate }}</label>
        </div>
      </div>
    </div>

    <!-- Contact Info -->
    <h4 class="section-title">{{ 'PARTNERS.CONTACT_INFO' | translate }}</h4>
    <div class="form-row">
      <div class="form-field">
        <label>{{ 'PARTNERS.EMAIL' | translate }}</label>
        <input pInputText formControlName="email" />
      </div>
      <div class="form-field">
        <label>{{ 'PARTNERS.PHONE' | translate }}</label>
        <input pInputText formControlName="phone" />
      </div>
    </div>
    <div class="form-row">
      <div class="form-field">
        <label>{{ 'PARTNERS.MOBILE' | translate }}</label>
        <input pInputText formControlName="mobile" />
      </div>
      <div class="form-field">
        <label>{{ 'PARTNERS.FAX' | translate }}</label>
        <input pInputText formControlName="fax" />
      </div>
    </div>
    <div class="form-field">
      <label>{{ 'PARTNERS.WEBSITE' | translate }}</label>
      <input pInputText formControlName="website" />
    </div>

    <!-- Financial Info -->
    <h4 class="section-title">{{ 'PARTNERS.FINANCIAL_INFO' | translate }}</h4>
    <div class="form-row">
      <div class="form-field">
        <label>{{ 'PARTNERS.TAX_NUMBER' | translate }}</label>
        <input pInputText formControlName="tax_number" />
      </div>
      <div class="form-field">
        <label>{{ 'PARTNERS.COMMERCIAL_REGISTER' | translate }}</label>
        <input pInputText formControlName="commercial_register" />
      </div>
    </div>
    <div class="form-row">
      <div class="form-field">
        <label>{{ 'PARTNERS.CREDIT_LIMIT' | translate }}</label>
        <p-inputNumber formControlName="credit_limit" [mode]="'decimal'" [minFractionDigits]="2" />
      </div>
      <div class="form-field">
        <label>{{ 'PARTNERS.PAYMENT_TERMS' | translate }}</label>
        <p-inputNumber formControlName="payment_terms_days" [suffix]="' days'" />
      </div>
    </div>
    <div class="form-row">
      @if (partnerForm.get('is_customer')?.value) {
        <div class="form-field">
          <label>{{ 'PARTNERS.AR_ACCOUNT' | translate }}</label>
          <p-select
            formControlName="ar_account_id"
            [options]="(accounts$ | async) || []"
            optionLabel="name"
            optionValue="id"
            [filter]="true"
            filterBy="name,name_ar,name_en,code"
            [showClear]="true"
            [placeholder]="'PARTNERS.SELECT_AR_ACCOUNT' | translate"
          />
          <small class="form-hint">{{ 'PARTNERS.AR_ACCOUNT_HINT' | translate }}</small>
        </div>
      }
      @if (partnerForm.get('is_supplier')?.value) {
        <div class="form-field">
          <label>{{ 'PARTNERS.AP_ACCOUNT' | translate }}</label>
          <p-select
            formControlName="ap_account_id"
            [options]="(accounts$ | async) || []"
            optionLabel="name"
            optionValue="id"
            [filter]="true"
            filterBy="name,name_ar,name_en,code"
            [showClear]="true"
            [placeholder]="'PARTNERS.SELECT_AP_ACCOUNT' | translate"
          />
          <small class="form-hint">{{ 'PARTNERS.AP_ACCOUNT_HINT' | translate }}</small>
        </div>
      }
    </div>

    <!-- Notes -->
    <div class="form-field">
      <label>{{ 'PARTNERS.NOTES' | translate }}</label>
      <input pInputText formControlName="notes" />
    </div>

    <!-- Contacts (edit only) -->
    @if (editingPartner()) {
      <h4 class="section-title">{{ 'PARTNERS.CONTACTS' | translate }}</h4>
      @if (contacts().length > 0) {
        <div class="sub-table">
          <table>
            <thead>
              <tr>
                <th>{{ 'PARTNERS.CONTACT_NAME' | translate }}</th>
                <th>{{ 'PARTNERS.POSITION' | translate }}</th>
                <th>{{ 'PARTNERS.PHONE' | translate }}</th>
                <th>{{ 'PARTNERS.EMAIL' | translate }}</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              @for (c of contacts(); track c.id) {
                <tr>
                  <td>
                    {{ c.name_ar || c.name }}
                    @if (c.is_primary) { <p-tag value="Primary" severity="info" styleClass="ms-1" /> }
                  </td>
                  <td>{{ c.position_ar || c.position || '—' }}</td>
                  <td>{{ c.phone || c.mobile || '—' }}</td>
                  <td>{{ c.email || '—' }}</td>
                  <td class="action-buttons">
                    <p-button icon="pi pi-pencil" [rounded]="true" [text]="true" severity="info" size="small" (onClick)="editContact(c)" />
                    <p-button icon="pi pi-trash" [rounded]="true" [text]="true" severity="danger" size="small" (onClick)="deleteContact(c)" />
                  </td>
                </tr>
              }
            </tbody>
          </table>
        </div>
      } @else {
        <p class="no-data-hint">{{ 'PARTNERS.NO_CONTACTS' | translate }}</p>
      }
      <p-button [label]="'PARTNERS.ADD_CONTACT' | translate" icon="pi pi-plus" severity="secondary" [outlined]="true" size="small" (onClick)="openNewContact()" />

      <!-- Addresses -->
      <h4 class="section-title">{{ 'PARTNERS.ADDRESSES' | translate }}</h4>
      @if (addresses().length > 0) {
        <div class="sub-table">
          <table>
            <thead>
              <tr>
                <th>{{ 'PARTNERS.ADDRESS_TYPE' | translate }}</th>
                <th>{{ 'PARTNERS.ADDRESS' | translate }}</th>
                <th>{{ 'PARTNERS.CITY' | translate }}</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              @for (a of addresses(); track a.id) {
                <tr>
                  <td>
                    <p-tag [value]="a.address_type_label || a.address_type" severity="info" />
                    @if (a.is_default) { <p-tag value="Default" severity="success" styleClass="ms-1" /> }
                  </td>
                  <td>{{ a.address_line_1 }}</td>
                  <td>{{ a.city || '—' }}</td>
                  <td class="action-buttons">
                    <p-button icon="pi pi-pencil" [rounded]="true" [text]="true" severity="info" size="small" (onClick)="editAddress(a)" />
                    <p-button icon="pi pi-trash" [rounded]="true" [text]="true" severity="danger" size="small" (onClick)="deleteAddress(a)" />
                  </td>
                </tr>
              }
            </tbody>
          </table>
        </div>
      } @else {
        <p class="no-data-hint">{{ 'PARTNERS.NO_ADDRESSES' | translate }}</p>
      }
      <p-button [label]="'PARTNERS.ADD_ADDRESS' | translate" icon="pi pi-plus" severity="secondary" [outlined]="true" size="small" (onClick)="openNewAddress()" />
    }
  </form>
</app-form-dialog>

<!-- Contact Form Dialog -->
<p-dialog
  [header]="editingContact() ? ('PARTNERS.EDIT_CONTACT' | translate) : ('PARTNERS.ADD_CONTACT' | translate)"
  [(visible)]="contactDialogVisible"
  [modal]="true"
  [style]="{ width: '550px' }"
>
  <form [formGroup]="contactForm" class="dialog-form">
    <div class="form-row">
      <div class="form-field">
        <label>{{ 'PARTNERS.CONTACT_NAME_AR' | translate }} *</label>
        <input pInputText formControlName="name_ar" />
      </div>
      <div class="form-field">
        <label>{{ 'PARTNERS.CONTACT_NAME_EN' | translate }}</label>
        <input pInputText formControlName="name" />
      </div>
    </div>
    <div class="form-row">
      <div class="form-field">
        <label>{{ 'PARTNERS.POSITION' | translate }}</label>
        <input pInputText formControlName="position_ar" />
      </div>
      <div class="form-field">
        <label>{{ 'PARTNERS.EMAIL' | translate }}</label>
        <input pInputText formControlName="email" />
      </div>
    </div>
    <div class="form-row">
      <div class="form-field">
        <label>{{ 'PARTNERS.PHONE' | translate }}</label>
        <input pInputText formControlName="phone" />
      </div>
      <div class="form-field">
        <label>{{ 'PARTNERS.MOBILE' | translate }}</label>
        <input pInputText formControlName="mobile" />
      </div>
    </div>
    <div class="form-field switch-row">
      <div class="switch-item">
        <p-toggleSwitch formControlName="is_primary" />
        <label>{{ 'PARTNERS.PRIMARY_CONTACT' | translate }}</label>
      </div>
    </div>
  </form>
  <ng-template #footer>
    <p-button [label]="'COMMON.CANCEL' | translate" icon="pi pi-times" severity="secondary" (onClick)="contactDialogVisible.set(false)" />
    <p-button [label]="'COMMON.SAVE' | translate" icon="pi pi-check" (onClick)="saveContact()" />
  </ng-template>
</p-dialog>

<!-- Address Form Dialog -->
<p-dialog
  [header]="editingAddress() ? ('PARTNERS.EDIT_ADDRESS' | translate) : ('PARTNERS.ADD_ADDRESS' | translate)"
  [(visible)]="addressDialogVisible"
  [modal]="true"
  [style]="{ width: '550px' }"
>
  <form [formGroup]="addressForm" class="dialog-form">
    <div class="form-row">
      <div class="form-field">
        <label>{{ 'PARTNERS.ADDRESS_TYPE' | translate }} *</label>
        <p-select formControlName="address_type" [options]="addressTypeOptions" optionLabel="label" optionValue="value" />
      </div>
      <div class="form-field switch-row">
        <div class="switch-item">
          <p-toggleSwitch formControlName="is_default" />
          <label>{{ 'PARTNERS.DEFAULT_ADDRESS' | translate }}</label>
        </div>
      </div>
    </div>
    <div class="form-field">
      <label>{{ 'PARTNERS.ADDRESS_LINE_1' | translate }} *</label>
      <input pInputText formControlName="address_line_1" />
    </div>
    <div class="form-field">
      <label>{{ 'PARTNERS.ADDRESS_LINE_2' | translate }}</label>
      <input pInputText formControlName="address_line_2" />
    </div>
    <div class="form-row">
      <div class="form-field">
        <label>{{ 'PARTNERS.CITY' | translate }}</label>
        <input pInputText formControlName="city" />
      </div>
      <div class="form-field">
        <label>{{ 'PARTNERS.GOVERNORATE' | translate }}</label>
        <input pInputText formControlName="governorate" />
      </div>
    </div>
    <div class="form-row">
      <div class="form-field">
        <label>{{ 'PARTNERS.COUNTRY_CODE' | translate }}</label>
        <input pInputText formControlName="country_code" />
      </div>
      <div class="form-field">
        <label>{{ 'PARTNERS.POSTAL_CODE' | translate }}</label>
        <input pInputText formControlName="postal_code" />
      </div>
    </div>
  </form>
  <ng-template #footer>
    <p-button [label]="'COMMON.CANCEL' | translate" icon="pi pi-times" severity="secondary" (onClick)="addressDialogVisible.set(false)" />
    <p-button [label]="'COMMON.SAVE' | translate" icon="pi pi-check" (onClick)="saveAddress()" />
  </ng-template>
</p-dialog>

<!-- Debt Changes Dialog -->
<p-dialog
  [header]="'PARTNERS.DEBT_CHANGES' | translate"
  [(visible)]="debtDialogVisible"
  [modal]="true"
  [style]="{ width: '650px' }"
>
  @if (debtChanges().length > 0) {
    <div class="sub-table">
      <table>
        <thead>
          <tr>
            <th>{{ 'COMMON.DATE' | translate }}</th>
            <th>{{ 'PARTNERS.DEBT_TYPE' | translate }}</th>
            <th>{{ 'PARTNERS.AMOUNT' | translate }}</th>
            <th>{{ 'PARTNERS.REASON' | translate }}</th>
            <th>{{ 'PARTNERS.REFERENCE' | translate }}</th>
          </tr>
        </thead>
        <tbody>
          @for (dc of debtChanges(); track dc.id || $index) {
            <tr>
              <td>{{ dc.date || (dc.created_at | date:'shortDate') }}</td>
              <td><p-tag [value]="dc.type" [severity]="dc.type === 'increase' ? 'danger' : 'success'" /></td>
              <td>{{ dc.amount | number:'1.2-3' }}</td>
              <td>{{ dc.reason_ar || dc.reason || '—' }}</td>
              <td>{{ dc.reference || '—' }}</td>
            </tr>
          }
        </tbody>
      </table>
    </div>
  }

  <h4 class="section-title" style="margin-top: 1rem">{{ 'PARTNERS.NEW_DEBT_CHANGE' | translate }}</h4>
  <form [formGroup]="debtForm" class="dialog-form">
    <div class="form-row">
      <div class="form-field">
        <label>{{ 'PARTNERS.DEBT_TYPE' | translate }}</label>
        <p-select formControlName="type" [options]="debtTypeOptions" optionLabel="label" optionValue="value" />
      </div>
      <div class="form-field">
        <label>{{ 'PARTNERS.AMOUNT' | translate }} *</label>
        <p-inputNumber formControlName="amount" [mode]="'decimal'" [minFractionDigits]="3" [maxFractionDigits]="3" />
      </div>
    </div>
    <div class="form-row">
      <div class="form-field">
        <label>{{ 'COMMON.DATE' | translate }}</label>
        <p-datepicker formControlName="date" dateFormat="yy-mm-dd" [showIcon]="true" />
      </div>
      <div class="form-field">
        <label>{{ 'PARTNERS.REFERENCE' | translate }}</label>
        <input pInputText formControlName="reference" />
      </div>
    </div>
    <div class="form-row">
      <div class="form-field">
        <label>{{ 'PARTNERS.REASON' | translate }}</label>
        <textarea pTextarea formControlName="reason" [rows]="2"></textarea>
      </div>
      <div class="form-field">
        <label>{{ 'PARTNERS.REASON_AR' | translate }}</label>
        <textarea pTextarea formControlName="reason_ar" [rows]="2"></textarea>
      </div>
    </div>
    <p-button [label]="'PARTNERS.ADD_DEBT_CHANGE' | translate" icon="pi pi-plus" (onClick)="onCreateDebtChange()" />
  </form>
</p-dialog>
