import { Component, inject, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
import { ApiService, LeadDetail } from '../../core/api.service';
import { LangService } from '../../core/lang.service';
import { stageBadge } from '../../core/stage';

@Component({
  selector: 'app-lead-detail',
  standalone: true,
  imports: [RouterLink, FormsModule],
  template: `
    <a routerLink="/leads" class="back">‹ {{ lang.t('back_to_leads') }}</a>

    @if (loading()) { <p class="muted">{{ lang.t('loading') }}</p> }
    @else if (lead()) {
      @if (lead(); as l) {
      <div class="head fade-in">
        <div>
          <h1>{{ l.contact?.name || '—' }}</h1>
          <p class="muted">{{ l.event_type }} · {{ l.attendees }} {{ lang.t('col_guests') }}</p>
        </div>
        <span class="badge {{ badge(l.stage) }}">{{ lang.stage(l.stage) }}</span>
      </div>

      @if (l.halls.length) {
        <div class="card card-pad convert fade-in">
          <div class="conv-row">
            <div class="field" style="margin:0">
              <label>{{ lang.t('event_date') }}</label>
              <input type="date" [(ngModel)]="eventDate" [min]="today" />
            </div>
            <button class="btn btn--gold" [disabled]="booking() || !eventDate" (click)="convert(l.id)">
              {{ booking() ? lang.t('processing') : lang.t('convert_to_booking') }} →
            </button>
          </div>
        </div>
      }

      <div class="grid fade-in">
        <div class="card card-pad">
          <h3>{{ lang.t('contact') }}</h3>
          <div class="kv"><span class="muted">{{ lang.t('col_contact') }}</span><span>{{ l.contact?.name }}</span></div>
          <div class="kv"><span class="muted">Phone</span><span dir="ltr">{{ l.contact?.mobile }}</span></div>
          @if (l.contact?.email) { <div class="kv"><span class="muted">Email</span><span dir="ltr">{{ l.contact?.email }}</span></div> }
          <div class="kv"><span class="muted">{{ lang.t('col_budget') }}</span><span>{{ l.budget_max ? lang.money(l.budget_max) : '—' }}</span></div>
          @if (l.candidate_dates?.length) { <div class="kv"><span class="muted">{{ lang.t('dates') }}</span><span [attr.dir]="datesIsFlexible(l.candidate_dates) ? null : 'ltr'">{{ datesLabel(l.candidate_dates) }}</span></div> }
        </div>

        <div class="card card-pad">
          <h3>{{ lang.t('selected_halls') }}
            @if (l.grand_total) { <span class="grand">{{ lang.t('grand_total') }}: {{ lang.money(l.grand_total) }}</span> }
          </h3>
          @if (l.halls.length) {
            @for (h of l.halls; track h.hall) {
              <div class="hall-blk">
                <div class="hall-top">
                  <span><strong>{{ h.hall }}</strong> @if (h.package) { <span class="muted">· {{ h.package }}</span> }</span>
                  <span class="hall-total">{{ lang.money(h.total) }}@if (h.score != null) { <span class="score"> · {{ h.score }}%</span> }</span>
                </div>
                @if (h.swaps.length) {
                  <div class="line"><span class="muted">{{ lang.t('swaps') }}</span>
                    <span>@for (s of h.swaps; track s.item) { <span class="pill">{{ s.label || s.item }} ({{ s.delta > 0 ? '+' : '' }}{{ lang.money(s.delta) }})</span> }</span>
                  </div>
                }
                @if (h.extras.length) {
                  <div class="line"><span class="muted">{{ lang.t('extras') }}</span>
                    <span>@for (e of h.extras; track e.name) { <span class="pill">{{ e.name }}@if (e.qty > 1) { ×{{ e.qty }} } (+{{ lang.money(e.price * e.qty) }})</span> }</span>
                  </div>
                }
                @if (h.addons.length) {
                  <div class="line"><span class="muted">{{ lang.t('addons_label') }}</span>
                    <span>@for (a of h.addons; track a.name) { <span class="pill">{{ a.name }}@if (a.qty > 1) { ×{{ a.qty }} } (+{{ lang.money(a.price * a.qty) }})</span> }</span>
                  </div>
                }
              </div>
            }
          } @else { <p class="muted">{{ lang.t('no_halls') }}</p> }
        </div>

        <div class="card card-pad">
          <h3>{{ lang.t('visits') }}</h3>
          @if (l.visits.length) {
            @for (v of l.visits; track v.date) {
              <div class="kv"><span dir="ltr">{{ v.date }} {{ v.time || '' }}</span><span class="badge badge--new">{{ v.status }}</span></div>
            }
          } @else { <p class="muted">{{ lang.t('no_visits') }}</p> }
        </div>
      </div>
      }
    }
  `,
  styles: [`
    .back { display: inline-block; margin-bottom: 18px; color: var(--ink-soft); font-weight: 600; }
    .back:hover { color: var(--gold-deep); }
    .head { display: flex; align-items: flex-start; justify-content: space-between; gap: 14px; margin-bottom: 24px; }
    .head h1 { margin-bottom: 4px; }
    .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 20px; align-items: start; }
    h3 { margin-bottom: 16px; }
    .kv { display: flex; justify-content: space-between; gap: 14px; padding: 9px 0; border-bottom: 1px dashed var(--line); }
    .kv:last-child { border-bottom: none; }
    .score { color: var(--gold-deep); font-weight: 600; }
    .grand { float: inline-end; font-size: .92rem; color: var(--gold-deep); font-weight: 700; }
    .hall-blk { padding: 12px 0; border-bottom: 1px solid var(--line); }
    .hall-blk:last-child { border-bottom: 0; }
    .hall-top { display: flex; justify-content: space-between; gap: 12px; align-items: baseline; }
    .hall-total { font-weight: 700; white-space: nowrap; }
    .line { display: flex; gap: 10px; margin-top: 6px; font-size: .86rem; align-items: baseline; }
    .line > .muted { flex: 0 0 84px; }
    .pill { display: inline-block; background: var(--bg); border: 1px solid var(--line); border-radius: 999px;
      padding: 2px 10px; margin: 0 4px 4px 0; font-size: .8rem; }
    .convert { margin-bottom: 20px; background: #fffdf8; border-color: var(--gold); }
    .conv-row { display: flex; align-items: flex-end; gap: 16px; flex-wrap: wrap; }
  `],
})
export class LeadDetailComponent {
  lang = inject(LangService);
  private api = inject(ApiService);
  private route = inject(ActivatedRoute);
  private router = inject(Router);

  lead = signal<LeadDetail | null>(null);
  loading = signal(true);
  badge = stageBadge;
  booking = signal(false);
  eventDate = '';
  today = new Date().toISOString().slice(0, 10);

  constructor() {
    const id = Number(this.route.snapshot.paramMap.get('id'));
    this.api.lead(id).subscribe({
      next: (r) => {
        this.lead.set(r.data.lead);
        this.eventDate = r.data.lead.candidate_dates?.[0] || '';
        this.loading.set(false);
      },
      error: () => this.loading.set(false),
    });
  }

  private static MONTHS_EN = ['January','February','March','April','May','June','July','August','September','October','November','December'];
  private static MONTHS_AR = ['يناير','فبراير','مارس','أبريل','مايو','يونيو','يوليو','أغسطس','سبتمبر','أكتوبر','نوفمبر','ديسمبر'];

  /** A "flexible month" lead = several dates all inside one calendar month. */
  datesIsFlexible(dates?: string[]): boolean {
    if (!dates || dates.length < 5) return false;
    return new Set(dates.map((d) => d.slice(0, 7))).size === 1;
  }

  datesLabel(dates?: string[]): string {
    if (!dates?.length) return '';
    if (this.datesIsFlexible(dates)) {
      const [y, m] = dates[0].split('-').map(Number);
      const months = this.lang.lang() === 'ar' ? LeadDetailComponent.MONTHS_AR : LeadDetailComponent.MONTHS_EN;
      return `${this.lang.t('flexible')} — ${months[m - 1]} ${y}`;
    }
    return dates.join(', ');
  }

  convert(leadId: number): void {
    this.booking.set(true);
    this.api.book(leadId, this.eventDate || undefined).subscribe({
      next: (r) => { this.booking.set(false); this.router.navigate(['/bookings', r.data.booking.id]); },
      error: () => this.booking.set(false),
    });
  }
}
