import { DatePipe } from '@angular/common';
import { Component, inject, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { ApiService, AssetRow, AssetMovement, HallOption } from '../../core/api.service';
import { LangService } from '../../core/lang.service';

@Component({
  selector: 'app-assets',
  standalone: true,
  imports: [FormsModule, DatePipe],
  template: `
    <div class="head">
      <h1>{{ lang.t('nav_assets') }}</h1>
      <div class="filters">
        <input class="filter search" [(ngModel)]="q" (ngModelChange)="onSearch()" [placeholder]="lang.t('search_assets')" />
        <select class="filter" [(ngModel)]="status" (ngModelChange)="reload()">
          <option value="">{{ lang.t('all_statuses') }}</option>
          @for (s of statuses(); track s) { <option [value]="s">{{ lang.t('ast_' + s) }}</option> }
        </select>
        <select class="filter" [(ngModel)]="category" (ngModelChange)="reload()">
          <option value="">{{ lang.t('all_categories') }}</option>
          @for (c of categories(); track c) { <option [value]="c">{{ c }}</option> }
        </select>
      </div>
    </div>

    <div class="card fade-in">
      @if (loading()) { <p class="muted pad">{{ lang.t('loading') }}</p> }
      @else if (assets().length) {
        <table class="tbl">
          <thead>
            <tr>
              <th>{{ lang.t('col_code') }}</th>
              <th>{{ lang.t('col_asset') }}</th>
              <th>{{ lang.t('col_category') }}</th>
              <th>{{ lang.t('col_qty') }}</th>
              <th>{{ lang.t('col_location') }}</th>
              <th>{{ lang.t('col_condition') }}</th>
              <th>{{ lang.t('col_status') }}</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            @for (a of assets(); track a.id) {
              <tr>
                <td class="mono">{{ a.code }}</td>
                <td><strong>{{ a.name }}</strong></td>
                <td><span class="chip">{{ a.category }}</span></td>
                <td>{{ a.quantity }}</td>
                <td>{{ a.hall_name || a.location_name || '—' }}</td>
                <td>{{ lang.t('cond_' + a.condition) }}</td>
                <td><span class="badge {{ statusClass(a.status) }}">{{ lang.t('ast_' + a.status) }}</span></td>
                <td class="actions">
                  @if (a.status !== 'retired') {
                    <button class="mini" (click)="openRelocate(a)">⇄ {{ lang.t('relocate') }}</button>
                  }
                  <button class="mini" (click)="openHistory(a)">↻ {{ lang.t('history') }}</button>
                </td>
              </tr>
            }
          </tbody>
        </table>
      } @else {
        <p class="muted pad">{{ lang.t('no_assets') }}</p>
      }
    </div>

    @if (relocating(); as a) {
      <div class="modal-bg" (click)="relocating.set(null)">
        <div class="modal" (click)="$event.stopPropagation()">
          <h3>{{ lang.t('relocate') }} — {{ a.name }}</h3>
          <p class="muted sm">{{ a.code }} · {{ lang.t('current') }}: {{ a.hall_name || a.location_name || '—' }}</p>
          <label>{{ lang.t('to_hall') }}</label>
          <select [(ngModel)]="toHall">
            <option value="">—</option>
            @for (h of halls(); track h.id) { <option [value]="h.id">{{ h.venue?.name ? h.venue?.name + ' · ' : '' }}{{ h.name }}</option> }
          </select>
          <label>{{ lang.t('col_condition') }}</label>
          <select [(ngModel)]="toCondition">
            @for (c of conditions; track c) { <option [value]="c">{{ lang.t('cond_' + c) }}</option> }
          </select>
          <label>{{ lang.t('notes') }}</label>
          <textarea [(ngModel)]="notes" rows="2"></textarea>
          @if (relocateErr()) { <p class="err">{{ relocateErr() }}</p> }
          <div class="modal-actions">
            <button class="btn btn--ghost" (click)="relocating.set(null)">{{ lang.t('cancel') }}</button>
            <button class="btn btn--gold" [disabled]="busy() || !toHall" (click)="doRelocate(a)">
              {{ busy() ? lang.t('processing') : lang.t('confirm') }}
            </button>
          </div>
        </div>
      </div>
    }

    @if (history(); as h) {
      <div class="modal-bg" (click)="history.set(null)">
        <div class="modal" (click)="$event.stopPropagation()">
          <h3>{{ lang.t('history') }} — {{ h.asset.name }}</h3>
          <p class="muted sm">{{ h.asset.code }}</p>
          @if (historyLoading()) { <p class="muted">{{ lang.t('loading') }}</p> }
          @else if (h.movements.length) {
            <ul class="timeline">
              @for (m of h.movements; track m.id) {
                <li>
                  <div class="tl-row">
                    <strong>{{ m.from || '—' }} → {{ m.to || '—' }}</strong>
                    <span class="muted sm">{{ m.at ? (m.at | date:'MMM d, HH:mm') : '' }}</span>
                  </div>
                  <div class="muted sm">{{ lang.t('reason') }}: {{ m.reason }} · {{ lang.t('cond_' + m.condition) }}@if (m.by) { · {{ m.by }} }</div>
                  @if (m.notes) { <div class="sm note">“{{ m.notes }}”</div> }
                </li>
              }
            </ul>
          } @else { <p class="muted">{{ lang.t('no_history') }}</p> }
          <div class="modal-actions"><button class="btn btn--ghost" (click)="history.set(null)">{{ lang.t('cancel') }}</button></div>
        </div>
      </div>
    }
  `,
  styles: [`
    .head { display: flex; align-items: center; justify-content: space-between; gap: 16px; flex-wrap: wrap; margin-bottom: 18px; }
    h1 { font-size: 1.5rem; }
    .filters { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
    .filter { border: 1px solid var(--line); background: #fff; border-radius: 9px; padding: 9px 14px; font-family: inherit; font-weight: 600; }
    .search { min-width: 200px; font-weight: 400; }
    .card { background: var(--panel); border: 1px solid var(--line); border-radius: 14px; overflow: hidden; }
    .pad { padding: 26px; }
    .tbl { width: 100%; border-collapse: collapse; }
    .tbl th { text-align: start; font-size: .78rem; text-transform: uppercase; letter-spacing: .5px; color: var(--ink-soft, #888);
      padding: 13px 16px; border-bottom: 1px solid var(--line); }
    .tbl td { padding: 13px 16px; border-bottom: 1px solid var(--line); font-size: .92rem; }
    .tbl tr:last-child td { border-bottom: 0; }
    .mono { font-family: ui-monospace, monospace; font-size: .85rem; color: var(--ink-soft, #666); }
    .chip { font-size: .74rem; font-weight: 600; text-transform: capitalize; padding: 2px 10px; border-radius: 999px; background: #efeae0; color: #6b6b6b; }
    .badge { font-size: .74rem; font-weight: 700; padding: 3px 11px; border-radius: 999px; }
    .b-ok { background: #e7f5ec; color: #1d7a46; }
    .b-use { background: #e9f0fb; color: #2a5db0; }
    .b-mnt { background: #fdeede; color: #b5691a; }
    .b-off { background: #efeae0; color: #777; }
    .mini { border: 1px solid var(--line); background: #fff; border-radius: 7px; padding: 5px 10px; font-family: inherit;
      font-weight: 600; font-size: .8rem; cursor: pointer; white-space: nowrap; }
    .mini:hover { border-color: var(--gold); color: var(--gold-deep); }
    .modal-bg { position: fixed; inset: 0; background: rgba(20,18,18,.5); display: flex; align-items: center; justify-content: center; z-index: 2000; padding: 20px; }
    .modal { background: var(--panel); border-radius: 14px; padding: 24px; width: 100%; max-width: 420px; box-shadow: 0 18px 50px rgba(0,0,0,.25); }
    .modal h3 { margin-bottom: 4px; }
    .modal .sm { font-size: .82rem; margin-bottom: 14px; }
    .modal label { display: block; font-size: .8rem; font-weight: 600; color: var(--ink-soft, #777); margin: 10px 0 4px; }
    .modal select, .modal textarea { width: 100%; border: 1px solid var(--line); border-radius: 9px; padding: 9px 12px; font-family: inherit; }
    .modal .err { color: var(--danger); font-size: .85rem; margin-top: 8px; }
    .modal-actions { display: flex; gap: 10px; justify-content: flex-end; margin-top: 18px; }
    .actions { white-space: nowrap; display: flex; gap: 6px; }
    .timeline { list-style: none; margin: 14px 0 0; padding: 0; max-height: 50vh; overflow-y: auto; }
    .timeline li { padding: 10px 0 10px 14px; border-inline-start: 2px solid var(--line); position: relative; }
    .timeline li::before { content: ''; position: absolute; inset-inline-start: -5px; top: 14px; width: 8px; height: 8px;
      border-radius: 50%; background: var(--gold); }
    .tl-row { display: flex; justify-content: space-between; gap: 10px; }
    .note { color: var(--ink-soft, #777); font-style: italic; margin-top: 2px; }
  `],
})
export class AssetsComponent {
  lang = inject(LangService);
  private api = inject(ApiService);
  private route = inject(ActivatedRoute);

  q = '';
  status = '';
  category = '';
  assets = signal<AssetRow[]>([]);
  categories = signal<string[]>([]);
  statuses = signal<string[]>([]);
  loading = signal(true);
  private searchTimer: ReturnType<typeof setTimeout> | null = null;

  // Relocate modal
  halls = signal<HallOption[]>([]);
  relocating = signal<AssetRow | null>(null);
  toHall = '';
  toCondition = 'good';
  notes = '';
  conditions = ['good', 'fair', 'worn', 'damaged'];
  busy = signal(false);
  relocateErr = signal('');
  // History modal
  history = signal<{ asset: { code: string; name: string }; movements: AssetMovement[] } | null>(null);
  historyLoading = signal(false);

  constructor() {
    this.status = this.route.snapshot.queryParamMap.get('status') || '';
    this.reload();
    this.api.halls().subscribe({ next: (r) => this.halls.set(r.data.halls), error: () => {} });
  }

  openRelocate(a: AssetRow): void {
    this.relocating.set(a);
    this.toHall = a.hall_id ? String(a.hall_id) : '';
    this.toCondition = a.condition || 'good';
    this.notes = '';
    this.relocateErr.set('');
  }

  openHistory(a: AssetRow): void {
    this.history.set({ asset: { code: a.code, name: a.name }, movements: [] });
    this.historyLoading.set(true);
    this.api.assetHistory(a.id).subscribe({
      next: (r) => { this.history.set(r.data); this.historyLoading.set(false); },
      error: () => { this.historyLoading.set(false); },
    });
  }

  doRelocate(a: AssetRow): void {
    if (!this.toHall) { return; }
    this.busy.set(true); this.relocateErr.set('');
    this.api.relocateAsset(a.id, { hall_id: Number(this.toHall), condition: this.toCondition, notes: this.notes || undefined }).subscribe({
      next: () => { this.busy.set(false); this.relocating.set(null); this.reload(); },
      error: (e) => { this.busy.set(false); this.relocateErr.set(e?.error?.message || this.lang.t('error')); },
    });
  }

  onSearch(): void {
    if (this.searchTimer) { clearTimeout(this.searchTimer); }
    this.searchTimer = setTimeout(() => this.reload(), 280);
  }

  reload(): void {
    this.loading.set(true);
    this.api.assetRegister(this.q || undefined, this.status || undefined, this.category || undefined).subscribe({
      next: (r) => {
        this.assets.set(r.data.assets);
        if (r.data.categories?.length) { this.categories.set(r.data.categories); }
        if (r.data.statuses?.length) { this.statuses.set(r.data.statuses); }
        this.loading.set(false);
      },
      error: () => { this.loading.set(false); },
    });
  }

  statusClass(s: string): string {
    return ({ available: 'b-ok', in_use: 'b-use', maintenance: 'b-mnt', retired: 'b-off' } as Record<string, string>)[s] || 'b-off';
  }
}
