import { DatePipe } from '@angular/common';
import { Component, inject, signal } from '@angular/core';
import { RouterLink } from '@angular/router';
import { ApiService, Dashboard } from '../../core/api.service';
import { LangService } from '../../core/lang.service';
import { stageBadge } from '../../core/stage';

@Component({
  selector: 'app-dashboard',
  standalone: true,
  imports: [RouterLink, DatePipe],
  template: `
    <h1>{{ lang.t('dash_title') }}</h1>

    @if (loading()) { <p class="muted">{{ lang.t('loading') }}</p> }
    @else if (data()) {
      @if (data(); as d) {
      @if (d.revenue; as r) {
        <div class="card revenue fade-in">
          <div class="rev-fig">
            <span class="rv-lbl">{{ lang.t('rev_invoiced') }}</span>
            <span class="rv-val">{{ lang.money(r.invoiced) }}</span>
          </div>
          <div class="rev-fig">
            <span class="rv-lbl">{{ lang.t('rev_collected') }}</span>
            <span class="rv-val ok">{{ lang.money(r.collected) }}</span>
          </div>
          <div class="rev-fig">
            <span class="rv-lbl">{{ lang.t('rev_due') }}</span>
            <span class="rv-val" [class.due]="r.due > 0">{{ lang.money(r.due) }}</span>
          </div>
          <div class="rev-prog">
            <div class="rv-bar"><span class="rv-fill" [style.width.%]="r.collected_pct"></span></div>
            <span class="rv-pct">{{ r.collected_pct }}% {{ lang.t('rev_collected_pct') }}</span>
          </div>
        </div>
      }
      <div class="kpis fade-in">
        <a routerLink="/leads" class="card kpi">
          <span class="k-val">{{ d.leads_total }}</span><span class="k-lbl">{{ lang.t('kpi_leads') }}</span>
        </a>
        <div class="card kpi"><span class="k-val">{{ d.bookings_total }}</span><span class="k-lbl">{{ lang.t('kpi_bookings') }}</span></div>
        <a routerLink="/tasks" class="card kpi">
          <span class="k-val">{{ d.tasks_open ?? 0 }}</span><span class="k-lbl">{{ lang.t('kpi_open_tasks') }}</span>
        </a>
        <a routerLink="/tasks" class="card kpi" [class.kpi--alert]="(d.tasks_overdue ?? 0) > 0">
          <span class="k-val">{{ d.tasks_overdue ?? 0 }}</span><span class="k-lbl">{{ lang.t('kpi_overdue') }}</span>
        </a>
        <div class="card kpi"><span class="k-val">{{ d.upcoming_visits }}</span><span class="k-lbl">{{ lang.t('kpi_visits') }}</span></div>
        <a routerLink="/assets" class="card kpi">
          <span class="k-val">{{ d.assets_total ?? 0 }}</span><span class="k-lbl">{{ lang.t('kpi_assets') }}</span>
        </a>
        <a routerLink="/assets" [queryParams]="{ status: 'maintenance' }" class="card kpi" [class.kpi--warn]="(d.assets_maintenance ?? 0) > 0">
          <span class="k-val">{{ d.assets_maintenance ?? 0 }}</span><span class="k-lbl">{{ lang.t('kpi_maintenance') }}</span>
        </a>
        <div class="card kpi"><span class="k-val">{{ d.halls_total }}</span><span class="k-lbl">{{ lang.t('kpi_halls') }}</span></div>
        <div class="card kpi"><span class="k-val">{{ d.venues_total }}</span><span class="k-lbl">{{ lang.t('kpi_venues') }}</span></div>
      </div>

      <div class="cols fade-in">
        <div class="card card-pad pipeline">
          <h3>{{ lang.t('pipeline') }}</h3>
          @if (stages(d).length) {
            @for (s of stages(d); track s.code) {
              <a routerLink="/leads" [queryParams]="{ stage: s.code }" class="prow">
                <span class="badge {{ badge(s.code) }}">{{ lang.stage(s.code) }}</span>
                <span class="bar"><span class="fill" [style.width.%]="pct(s.count, d)"></span></span>
                <strong>{{ s.count }}</strong>
              </a>
            }
          } @else { <p class="muted">{{ lang.t('no_leads') }}</p> }
        </div>

        <div class="card card-pad">
          <h3>{{ lang.t('upcoming_events') }}</h3>
          @if (d.upcoming_bookings?.length) {
            @for (b of d.upcoming_bookings!; track b.id) {
              <a [routerLink]="['/bookings', b.id]" class="erow">
                <span class="edate">{{ b.event_date | date:'MMM d' }}</span>
                <span class="emain">
                  <strong>{{ b.contact || b.booking_no }}</strong>
                  <span class="muted sm">{{ b.event_type || '' }}@if (b.attendees) { · {{ b.attendees }} {{ lang.t('guests') }} }</span>
                </span>
                <span class="badge {{ b.status === 'confirmed' ? 'badge--won' : 'badge--warm' }}">{{ lang.t(b.status === 'confirmed' ? 'confirmed' : 'tentative') }}</span>
              </a>
            }
          } @else { <p class="muted">{{ lang.t('no_upcoming') }}</p> }
        </div>
      </div>
      }
    }
  `,
  styles: [`
    h1 { margin-bottom: 22px; }
    .revenue { display: grid; grid-template-columns: repeat(3, 1fr) 1.4fr; gap: 22px; align-items: center; padding: 20px 24px; margin-bottom: 18px; }
    @media (max-width: 760px) { .revenue { grid-template-columns: 1fr 1fr; } }
    .rev-fig { display: flex; flex-direction: column; gap: 3px; }
    .rv-lbl { color: var(--ink-soft); font-size: .82rem; }
    .rv-val { font-size: 1.45rem; font-weight: 700; }
    .rv-val.ok { color: #1d7a46; }
    .rv-val.due { color: #b5691a; }
    .rev-prog { display: flex; flex-direction: column; gap: 6px; }
    .rv-bar { height: 9px; background: var(--bg); border-radius: 999px; overflow: hidden; }
    .rv-fill { display: block; height: 100%; background: linear-gradient(90deg, #2e9e5b, #1d7a46); }
    .rv-pct { font-size: .8rem; color: var(--ink-soft); }
    .kpis { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 18px; margin-bottom: 24px; }
    .kpi { padding: 22px; display: flex; flex-direction: column; gap: 4px; }
    a.kpi:hover { border-color: var(--gold); }
    .k-val { font-size: 2.1rem; font-weight: 700; line-height: 1; }
    .k-lbl { color: var(--ink-soft); font-size: .9rem; }
    .kpi--alert { border-color: #e2b4ac; background: #fff6f5; }
    .kpi--alert .k-val { color: var(--danger); }
    .kpi--warn { border-color: #e6cda0; background: #fffaf0; }
    .kpi--warn .k-val { color: #b5691a; }
    .cols { display: grid; grid-template-columns: 1fr 1fr; gap: 18px; align-items: start; }
    @media (max-width: 860px) { .cols { grid-template-columns: 1fr; } }
    .card-pad h3 { margin-bottom: 16px; }
    .erow { display: grid; grid-template-columns: 56px 1fr auto; align-items: center; gap: 12px; padding: 10px 0; border-bottom: 1px dashed var(--line); }
    .erow:last-child { border-bottom: 0; }
    .erow:hover { background: var(--bg); }
    .edate { font-weight: 700; color: var(--gold-deep); font-size: .92rem; text-align: center; }
    .emain { display: flex; flex-direction: column; min-width: 0; }
    .emain .sm { font-size: .82rem; }
    .pipeline h3 { margin-bottom: 18px; }
    .prow { display: grid; grid-template-columns: 200px 1fr 40px; align-items: center; gap: 16px; padding: 9px 0; }
    .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)); }
    .prow strong { text-align: end; }
    @media (max-width: 560px) { .prow { grid-template-columns: 1fr 36px; } .bar { display: none; } }
  `],
})
export class DashboardComponent {
  lang = inject(LangService);
  private api = inject(ApiService);

  data = signal<Dashboard | null>(null);
  loading = signal(true);

  constructor() {
    this.api.dashboard().subscribe({
      next: (r) => { this.data.set(r.data); this.loading.set(false); },
      error: () => this.loading.set(false),
    });
  }

  badge = stageBadge;

  stages(d: Dashboard): { code: string; count: number }[] {
    return Object.entries(d.leads_by_stage || {}).map(([code, count]) => ({ code, count: count as number }))
      .sort((a, b) => b.count - a.count);
  }
  pct(count: number, d: Dashboard): number {
    const max = Math.max(1, ...Object.values(d.leads_by_stage || {}).map((v) => v as number));
    return Math.round((count / max) * 100);
  }
}
