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

interface Opt { value: string; ar: string; en: string; }

@Component({
  selector: 'app-match',
  standalone: true,
  imports: [FormsModule],
  template: `
    <h1>{{ lang.t('match_title') }}</h1>
    <p class="muted sub">{{ lang.t('match_sub') }}</p>

    <div class="layout">
      <div class="card card-pad form fade-in">
        <div class="field">
          <label>{{ lang.t('attendees') }}</label>
          <input type="number" min="0" [(ngModel)]="attendees" placeholder="250" />
        </div>
        <div class="field">
          <label>{{ lang.t('fnb_level') }}</label>
          <select [(ngModel)]="fnb">
            <option value="">{{ lang.t('please_select') }}</option>
            @for (o of fnbLevels; track o.value) { <option [value]="o.value">{{ label(o) }}</option> }
          </select>
        </div>
        <div class="field">
          <label>{{ lang.t('venue_type') }}</label>
          <select [(ngModel)]="venue">
            <option value="">{{ lang.t('please_select') }}</option>
            @for (o of venueTypes; track o.value) { <option [value]="o.value">{{ label(o) }}</option> }
          </select>
        </div>
        <div class="field">
          <label>{{ lang.t('area') }}</label>
          <select [(ngModel)]="areaId">
            <option [ngValue]="null">{{ lang.t('please_select') }}</option>
            @for (a of areas(); track a.id) { <option [ngValue]="a.id">{{ lang.lang() === 'ar' ? (a.name_ar || a.name) : a.name }}</option> }
          </select>
        </div>
        <div class="field">
          <label>{{ lang.t('budget') }}</label>
          <input type="number" min="0" step="1000" [(ngModel)]="budget" placeholder="200000" />
        </div>
        <button class="btn btn--gold btn--block" [disabled]="busy()" (click)="run()">
          {{ busy() ? lang.t('loading') : lang.t('run_match') }}
        </button>
      </div>

      <div class="results">
        @if (ran()) {
          <p class="summary"><strong>{{ matchedCount() }}</strong> {{ lang.t('matched_of') }} {{ results().length }} {{ lang.t('halls') }} — {{ lang.t('at_threshold') }} {{ threshold() }}%</p>
          @for (r of results(); track r.hall_id) {
            <div class="card res fade-in" [class.is-match]="r.matched">
              <div class="r-top">
                <div>
                  <strong>{{ r.hall_name }}</strong>
                  <span class="venue muted"> · {{ r.venue_name }}</span>
                </div>
                <span class="badge" [class.badge--won]="r.matched" [class.badge--muted]="!r.matched">
                  {{ r.matched ? lang.t('match_badge') : lang.t('below') }} · {{ r.score }}%
                </span>
              </div>
              <div class="bar"><span class="fill" [class.fill--off]="!r.matched" [style.width.%]="r.score"></span></div>
              @if (r.reasons.length) {
                <div class="reasons">
                  <span class="muted sm">{{ lang.t('why_not') }}:</span>
                  <ul>@for (x of r.reasons; track x) { <li>{{ x }}</li> }</ul>
                </div>
              }
            </div>
          }
        } @else {
          <div class="card card-pad center muted empty">{{ lang.t('match_sub') }}</div>
        }
      </div>
    </div>
  `,
  styles: [`
    h1 { margin-bottom: 4px; }
    .sub { margin-bottom: 24px; max-width: 640px; }
    .layout { display: grid; grid-template-columns: 320px 1fr; gap: 24px; align-items: start; }
    .summary { margin: 0 0 16px; }
    .res { padding: 16px 18px; margin-bottom: 12px; }
    .res.is-match { border-color: var(--gold); }
    .r-top { display: flex; justify-content: space-between; align-items: center; gap: 10px; margin-bottom: 10px; }
    .venue { font-weight: 400; }
    .bar { height: 8px; background: var(--bg); border-radius: 999px; overflow: hidden; }
    .fill { display: block; height: 100%; background: linear-gradient(90deg, var(--gold), var(--gold-deep)); }
    .fill--off { background: #d7c9ad; }
    .reasons { margin-top: 12px; }
    .reasons ul { margin: 6px 0 0; padding-inline-start: 18px; }
    .reasons li { font-size: .86rem; color: var(--ink-soft); }
    .sm { font-size: .82rem; }
    .empty { padding: 60px 24px; }
    @media (max-width: 820px) { .layout { grid-template-columns: 1fr; } }
  `],
})
export class MatchComponent {
  lang = inject(LangService);
  private api = inject(ApiService);

  attendees: number | null = null;
  fnb = '';
  venue = '';
  areaId: number | null = null;
  budget: number | null = null;

  busy = signal(false);
  ran = signal(false);
  results = signal<MatchResult[]>([]);
  matchedCount = signal(0);
  threshold = signal(60);
  areas = signal<{ id: number; name: string; name_ar?: string }[]>([]);

  fnbLevels: Opt[] = [
    { value: 'high_tea', ar: 'شاي راقٍ', en: 'High Tea' },
    { value: 'drinks_only', ar: 'مشروبات فقط', en: 'Drinks only' },
    { value: 'set_menu', ar: 'منيو محدد', en: 'Set menu' },
    { value: 'open_buffet', ar: 'بوفيه مفتوح', en: 'Open buffet' },
    { value: 'custom', ar: 'مخصص', en: 'Custom' },
  ];
  venueTypes: Opt[] = [
    { value: 'open', ar: 'مفتوحة', en: 'Open-air' },
    { value: 'closed', ar: 'مغلقة', en: 'Indoor' },
    { value: 'both', ar: 'كلاهما', en: 'Both' },
  ];

  constructor() {
    this.api.reference().subscribe({ next: (r) => this.areas.set(r.data.areas || []), error: () => {} });
  }

  label(o: Opt): string { return this.lang.lang() === 'ar' ? o.ar : o.en; }

  run(): void {
    this.busy.set(true);
    const criteria: any = {};
    if (this.attendees) criteria.attendees = this.attendees;
    if (this.fnb) criteria.fnb_level = this.fnb;
    if (this.venue) criteria.venue_preference = this.venue;
    if (this.areaId) criteria.area_id = this.areaId;
    if (this.budget) criteria.budget = this.budget;

    this.api.match(criteria).subscribe({
      next: (r) => {
        this.results.set(r.data.results);
        this.matchedCount.set(r.data.matched_count);
        this.threshold.set(r.data.threshold);
        this.ran.set(true);
        this.busy.set(false);
      },
      error: () => this.busy.set(false),
    });
  }
}
