import { Component, inject, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ApiService, AssetOption, HallOption, TransferDetail, TransferRow } from '../../core/api.service';
import { LangService } from '../../core/lang.service';

interface TransferLine { name: string; kind: string; quantity: number; asset_id: number | null; }

@Component({
  selector: 'app-transfers',
  standalone: true,
  imports: [FormsModule],
  template: `
    <!-- LIST -->
    @if (mode() === 'list') {
      <div class="head">
        <h1>{{ lang.t('nav_transfers') }}</h1>
        <button class="btn btn--gold" (click)="openNew()">{{ lang.t('new_transfer') }}</button>
      </div>
      <div class="card fade-in">
        @if (loading()) { <p class="muted pad">{{ lang.t('loading') }}</p> }
        @else if (rows().length) {
          <table class="tbl">
            <thead><tr>
              <th>#</th><th>{{ lang.t('to_hall') }}</th><th>{{ lang.t('item_name') }}</th>
              <th>{{ lang.t('col_stage') }}</th><th></th>
            </tr></thead>
            <tbody>
              @for (t of rows(); track t.id) {
                <tr>
                  <td>#{{ t.id }}</td>
                  <td>{{ t.to_hall || '—' }}</td>
                  <td>{{ t.items_count }} {{ lang.t('items_word') }}</td>
                  <td><span class="badge {{ trBadge(t.status) }}">{{ trLabel(t.status) }}</span></td>
                  <td class="text-end">
                    @if (t.status === 'requested') {
                      <button class="btn btn--sm" (click)="openAccept(t.id)">{{ lang.t('accept') }}</button>
                    }
                  </td>
                </tr>
              }
            </tbody>
          </table>
        } @else { <p class="muted pad">{{ lang.t('no_transfers') }}</p> }
      </div>
    }

    <!-- NEW -->
    @if (mode() === 'new') {
      <a class="back" (click)="mode.set('list')">‹ {{ lang.t('back_to_transfers') }}</a>
      <h1>{{ lang.t('new_transfer') }}</h1>
      <div class="card card-pad fade-in form">
        <div class="field">
          <label>{{ lang.t('to_hall') }}</label>
          <select [(ngModel)]="toHall">
            <option [ngValue]="null">{{ lang.t('please_select') }}</option>
            @for (h of halls(); track h.id) { <option [ngValue]="h.id">{{ h.venue?.name }} — {{ h.name }}</option> }
          </select>
        </div>

        <table class="tbl items">
          <thead><tr><th>{{ lang.t('item_name') }}</th><th style="width:130px">{{ lang.t('kind') }}</th><th style="width:90px">{{ lang.t('quantity') }}</th><th></th></tr></thead>
          <tbody>
            @for (it of items(); track $index) {
              <tr>
                <td>
                  @if (it.kind === 'asset') {
                    <select [(ngModel)]="it.asset_id" (ngModelChange)="onAssetPick(it)">
                      <option [ngValue]="null">{{ lang.t('select_asset') }}</option>
                      @for (a of assets(); track a.id) {
                        <option [ngValue]="a.id">{{ a.code }} · {{ a.name }} ({{ a.quantity }})</option>
                      }
                    </select>
                  } @else {
                    <input type="text" [(ngModel)]="it.name" [placeholder]="lang.t('item_name')" />
                  }
                </td>
                <td>
                  <select [(ngModel)]="it.kind" (ngModelChange)="onKindChange(it)">
                    <option value="consumable">{{ lang.t('consumable') }}</option>
                    <option value="asset">{{ lang.t('asset') }}</option>
                  </select>
                </td>
                <td><input type="number" min="0" [(ngModel)]="it.quantity" /></td>
                <td><button class="rm" (click)="removeItem($index)">✕</button></td>
              </tr>
            }
          </tbody>
        </table>
        <button class="btn btn--ghost btn--sm" (click)="addItem()">{{ lang.t('add_item') }}</button>

        <div style="margin-top:20px;">
          <button class="btn btn--gold" [disabled]="busy() || !toHall || !validItems()" (click)="submit()">
            {{ busy() ? lang.t('processing') : lang.t('submit_request') }}
          </button>
        </div>
      </div>
    }

    <!-- ACCEPT -->
    @if (mode() === 'accept') {
      <a class="back" (click)="mode.set('list')">‹ {{ lang.t('back_to_transfers') }}</a>
      <h1>{{ lang.t('accept_transfer') }} #{{ detail()?.id }}</h1>
      @if (detail(); as d) {
        <div class="card card-pad fade-in form">
          <table class="tbl items">
            <thead><tr><th>{{ lang.t('item_name') }}</th><th>{{ lang.t('requested_word') }}</th><th style="width:120px">{{ lang.t('accepted_qty') }}</th><th style="width:140px">{{ lang.t('condition') }}</th></tr></thead>
            <tbody>
              @for (it of d.items; track it.id) {
                <tr>
                  <td>{{ it.name }} <small class="muted">({{ it.kind === 'asset' ? lang.t('asset') : lang.t('consumable') }})</small></td>
                  <td>{{ it.quantity }}</td>
                  <td><input type="number" min="0" [(ngModel)]="accept[it.id].accepted_quantity" /></td>
                  <td>
                    <select [(ngModel)]="accept[it.id].condition">
                      <option value="good">{{ lang.t('c_good') }}</option>
                      <option value="short">{{ lang.t('c_short') }}</option>
                      <option value="damaged">{{ lang.t('c_damaged') }}</option>
                    </select>
                  </td>
                </tr>
              }
            </tbody>
          </table>
          <div style="margin-top:18px;">
            <button class="btn btn--gold" [disabled]="busy()" (click)="confirmAccept(d.id)">
              {{ busy() ? lang.t('processing') : lang.t('confirm_accept') }}
            </button>
          </div>
        </div>
      }
    }
  `,
  styles: [`
    .head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 20px; }
    .pad { padding: 26px; }
    .text-end { text-align: end; }
    .back { display: inline-block; margin-bottom: 12px; color: var(--ink-soft); font-weight: 600; cursor: pointer; }
    .back:hover { color: var(--gold-deep); }
    .form { max-width: 720px; }
    .items input, .items select { width: 100%; padding: 8px 10px; border: 1px solid var(--line); border-radius: 7px; font-family: inherit; background: #fff; }
    .items td { padding: 8px; }
    .rm { background: none; border: none; color: var(--danger); cursor: pointer; font-weight: 700; }
  `],
})
export class TransfersComponent {
  lang = inject(LangService);
  private api = inject(ApiService);

  mode = signal<'list' | 'new' | 'accept'>('list');
  loading = signal(true);
  busy = signal(false);
  rows = signal<TransferRow[]>([]);
  halls = signal<HallOption[]>([]);
  assets = signal<AssetOption[]>([]);
  detail = signal<TransferDetail | null>(null);

  toHall: number | null = null;
  items = signal<TransferLine[]>([{ name: '', kind: 'consumable', quantity: 1, asset_id: null }]);
  accept: Record<number, { accepted_quantity: number; condition: string }> = {};

  private labels: Record<string, { badge: string; key: string }> = {
    requested: { badge: 'badge--warm', key: 'tr_requested' },
    in_transit: { badge: 'badge--new', key: 'tr_requested' },
    accepted: { badge: 'badge--won', key: 'tr_accepted' },
    rejected: { badge: 'badge--lost', key: 'tr_rejected' },
    cancelled: { badge: 'badge--muted', key: 'tr_cancelled' },
  };

  constructor() { this.load(); }

  load(): void {
    this.loading.set(true);
    this.api.transfers().subscribe({
      next: (r) => { this.rows.set(r.data.transfers.data); this.loading.set(false); },
      error: () => this.loading.set(false),
    });
  }

  trBadge(s: string): string { return this.labels[s]?.badge || 'badge--muted'; }
  trLabel(s: string): string { return this.lang.t(this.labels[s]?.key || s); }

  openNew(): void {
    this.toHall = null;
    this.items.set([{ name: '', kind: 'consumable', quantity: 1, asset_id: null }]);
    if (!this.halls().length) {
      this.api.halls().subscribe({ next: (r) => this.halls.set(r.data.halls), error: () => {} });
    }
    if (!this.assets().length) {
      this.api.assets().subscribe({ next: (r) => this.assets.set(r.data.assets), error: () => {} });
    }
    this.mode.set('new');
  }
  addItem(): void { this.items.set([...this.items(), { name: '', kind: 'consumable', quantity: 1, asset_id: null }]); }
  removeItem(i: number): void { this.items.set(this.items().filter((_, idx) => idx !== i)); }

  /** Switching kind clears the line's identity (free-text vs picked asset). */
  onKindChange(it: TransferLine): void { it.name = ''; it.asset_id = null; }

  /** When an asset is picked, copy its name (and default the quantity) onto the line. */
  onAssetPick(it: TransferLine): void {
    const a = this.assets().find((x) => x.id === it.asset_id);
    if (a) { it.name = a.name; if (!it.quantity || it.quantity < 1) it.quantity = a.quantity; }
  }

  private lineFilled = (it: TransferLine): boolean => (it.kind === 'asset' ? !!it.asset_id : !!it.name.trim());
  validItems(): boolean { return this.items().some((it) => this.lineFilled(it) && it.quantity > 0); }

  submit(): void {
    this.busy.set(true);
    const payload = {
      type: 'warehouse_to_hall',
      to_hall_id: this.toHall,
      items: this.items().filter(this.lineFilled).map((it) => ({
        name: it.name, kind: it.kind, quantity: it.quantity,
        asset_id: it.kind === 'asset' ? it.asset_id : undefined,
      })),
    };
    this.api.createTransfer(payload).subscribe({
      next: () => { this.busy.set(false); this.mode.set('list'); this.load(); },
      error: () => this.busy.set(false),
    });
  }

  openAccept(id: number): void {
    this.api.transfer(id).subscribe({
      next: (r) => {
        const d = r.data.transfer;
        this.accept = {};
        d.items.forEach((it) => (this.accept[it.id] = { accepted_quantity: it.quantity, condition: 'good' }));
        this.detail.set(d);
        this.mode.set('accept');
      },
      error: () => {},
    });
  }

  confirmAccept(id: number): void {
    this.busy.set(true);
    this.api.acceptTransfer(id, this.accept).subscribe({
      next: () => { this.busy.set(false); this.mode.set('list'); this.load(); },
      error: () => this.busy.set(false),
    });
  }
}
