'use client';

/**
 * Cross-Campaign-Dashboard (Phase 4).
 *
 * Top-Level-Tab, der KPIs der letzten N Tage über alle Workspaces aggregiert.
 *
 * Sektionen:
 *  - KPI-Tiles: Versendet, Verified Open-Rate (ohne Apple-MPP), Pixel gesamt, Click-Rate, …
 *  - Workspace-Vergleich: Tabelle mit Per-Workspace-Aggregaten
 *  - Top-Campaigns: nach Conversion-Wert sortiert
 *  - Hot Leads: Recipients der letzten 24h die geklickt haben + ≥1 Behavior-Event
 *
 * Datenquelle: GET /api/dashboard/overview?days=30
 */

import { useCallback, useEffect, useState } from 'react';
import {
  BarChart3,
  Loader2,
  AlertTriangle,
  RefreshCw,
  MailCheck,
  ShieldCheck,
  MousePointerClick,
  BadgeEuro,
  Flame,
  Trophy,
} from 'lucide-react';
import { cn } from '@/lib/utils';

interface Totals {
  campaigns: number;
  sent: number;
  delivered: number;
  verifiedOpens: number;
  /** Open-Pixel distinct, inkl. Apple Mail Privacy (MPP). */
  rawOpens: number;
  clicks: number;
  conversions: number;
  conversionValue: number;
}

interface BrandStats {
  slug: string;
  name: string;
  sent: number;
  delivered: number;
  verifiedOpens: number;
  rawOpens: number;
  clicks: number;
  conversions: number;
  conversionValue: number;
}

interface TopCampaign {
  id: string;
  name: string;
  workspaceSlug: string;
  sent: number;
  verifiedOpens: number;
  rawOpens: number;
  clicks: number;
  conversions: number;
  conversionValue: number;
}

interface HotLead {
  recipientId: string;
  email: string;
  firstName: string | null;
  lastName: string | null;
  campaignName: string;
  workspaceSlug: string;
  clickedAt: string;
  behaviorCount: number;
}

interface DashboardResponse {
  ok: boolean;
  range: { fromIso: string; toIso: string; days: number };
  totals: Totals;
  byBrand: BrandStats[];
  topCampaigns: TopCampaign[];
  hotLeads: HotLead[];
}

function fmtEuro(value: number): string {
  return new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR', maximumFractionDigits: 0 }).format(value);
}

function fmtPct(num: number, denom: number): string {
  if (denom === 0) return '—';
  return `${((num / denom) * 100).toFixed(1)}%`;
}

function fmtName(r: HotLead): string {
  const fn = [r.firstName, r.lastName].filter(Boolean).join(' ').trim();
  return fn || r.email;
}

function fmtTime(iso: string): string {
  const d = new Date(iso);
  if (Number.isNaN(d.getTime())) return iso;
  return d.toLocaleString('de-DE', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' });
}

export interface DashboardPanelProps {
  className?: string;
}

export function DashboardPanel({ className }: DashboardPanelProps) {
  const [data, setData] = useState<DashboardResponse | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [days, setDays] = useState(30);

  const fetchData = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await fetch(`/api/dashboard/overview?days=${days}`);
      if (!res.ok) throw new Error(`Dashboard-Lookup fehlgeschlagen (${res.status})`);
      const json = (await res.json()) as DashboardResponse;
      setData(json);
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Dashboard-Lookup fehlgeschlagen');
    } finally {
      setLoading(false);
    }
  }, [days]);

  useEffect(() => { void fetchData(); }, [fetchData]);

  return (
    <div className={cn('flex flex-col gap-6 px-6 py-6', className)}>
      {/* ─── Header ─────────────────────────────────────────────── */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <BarChart3 className="h-5 w-5 text-zinc-500" />
          <h1 className="text-lg font-semibold text-zinc-900 dark:text-zinc-100">Dashboard</h1>
          <span className="text-[11px] text-zinc-500">· Cross-Workspace-Übersicht</span>
        </div>
        <div className="flex items-center gap-2">
          <select
            value={days}
            onChange={(e) => setDays(Number(e.target.value))}
            className="rounded-md border border-zinc-200 bg-white px-2 py-1 text-xs text-zinc-700 dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-300"
          >
            <option value={7}>Letzte 7 Tage</option>
            <option value={14}>Letzte 14 Tage</option>
            <option value={30}>Letzte 30 Tage</option>
            <option value={90}>Letzte 90 Tage</option>
          </select>
          <button
            type="button"
            onClick={() => void fetchData()}
            disabled={loading}
            className="inline-flex items-center gap-1.5 rounded-md border border-zinc-200 bg-white px-2.5 py-1 text-xs text-zinc-700 transition hover:bg-zinc-50 disabled:opacity-50 dark:border-zinc-700 dark:bg-zinc-900 dark:text-zinc-300 dark:hover:bg-zinc-800"
          >
            {loading ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <RefreshCw className="h-3.5 w-3.5" />}
            Refresh
          </button>
        </div>
      </div>

      {error && (
        <div className="flex items-start gap-2 rounded-md border border-red-200 bg-red-50 px-3 py-2 text-xs text-red-800 dark:border-red-900/50 dark:bg-red-950/30">
          <AlertTriangle className="h-4 w-4 mt-0.5" />
          <span>{error}</span>
        </div>
      )}

      {!data && loading && (
        <div className="flex items-center justify-center py-12 text-sm text-zinc-500">
          <Loader2 className="mr-2 h-4 w-4 animate-spin" /> Lade Dashboard…
        </div>
      )}

      {data && (
        <>
          {/* ─── KPI-Tiles ──────────────────────────────────────── */}
          <div className="grid grid-cols-2 gap-3 md:grid-cols-5">
            <KpiTile
              icon={<MailCheck className="h-3.5 w-3.5" />}
              label="Versendet"
              value={data.totals.delivered.toLocaleString('de-DE')}
              sub={`${data.totals.campaigns} Campaigns`}
            />
            <KpiTile
              icon={<ShieldCheck className="h-3.5 w-3.5" />}
              label="Verified Open"
              title="Nur Pixel-Opens, die nicht als Apple Mail Privacy Protection (MPP) erkannt wurden. Klicks ohne Bild-Laden zählen nicht."
              value={fmtPct(data.totals.verifiedOpens, data.totals.delivered)}
              sub={`${data.totals.verifiedOpens.toLocaleString('de-DE')} verifiziert · ${data.totals.rawOpens.toLocaleString('de-DE')} Pixel gesamt (inkl. MPP)`}
            />
            <KpiTile
              icon={<MousePointerClick className="h-3.5 w-3.5" />}
              label="Click-Rate"
              value={fmtPct(data.totals.clicks, data.totals.delivered)}
              sub={`${data.totals.clicks.toLocaleString('de-DE')} unique`}
            />
            <KpiTile
              icon={<BadgeEuro className="h-3.5 w-3.5" />}
              label="Conversion"
              value={fmtPct(data.totals.conversions, data.totals.delivered)}
              sub={`${data.totals.conversions.toLocaleString('de-DE')} Events`}
            />
            <KpiTile
              icon={<Trophy className="h-3.5 w-3.5" />}
              label="Conversion-Wert"
              value={fmtEuro(data.totals.conversionValue)}
              sub="Summe Wert-Spalte"
            />
          </div>

          {/* ─── Workspace-Vergleich ────────────────────────────────── */}
          {data.byBrand.length > 0 && (
            <Section title="Workspace-Vergleich">
              <div className="overflow-hidden rounded-lg border border-zinc-200 bg-white dark:border-zinc-700 dark:bg-zinc-900">
                <table className="w-full text-xs">
                  <thead className="border-b border-zinc-200 bg-zinc-50 text-left text-[11px] uppercase tracking-wider text-zinc-500 dark:border-zinc-700 dark:bg-zinc-800/50">
                    <tr>
                      <th className="px-3 py-2">Workspace</th>
                      <th className="px-3 py-2 text-right">Sent</th>
                      <th className="px-3 py-2 text-right">Verified Open</th>
                      <th className="px-3 py-2 text-right" title="Alle Open-Pixel (inkl. Apple-MPP-Vorabladen)">
                        Pixel (gesamt)
                      </th>
                      <th className="px-3 py-2 text-right">Click-Rate</th>
                      <th className="px-3 py-2 text-right">Conversion</th>
                      <th className="px-3 py-2 text-right">Wert</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-zinc-100 dark:divide-zinc-800">
                    {data.byBrand.map((b) => (
                      <tr key={b.slug}>
                        <td className="px-3 py-2 font-medium text-zinc-900 dark:text-zinc-100">{b.name}</td>
                        <td className="px-3 py-2 text-right text-zinc-700 dark:text-zinc-300">{b.delivered.toLocaleString('de-DE')}</td>
                        <td className="px-3 py-2 text-right text-zinc-700 dark:text-zinc-300">{fmtPct(b.verifiedOpens, b.delivered)}</td>
                        <td className="px-3 py-2 text-right text-zinc-700 dark:text-zinc-300">{fmtPct(b.rawOpens, b.delivered)}</td>
                        <td className="px-3 py-2 text-right text-zinc-700 dark:text-zinc-300">{fmtPct(b.clicks, b.delivered)}</td>
                        <td className="px-3 py-2 text-right text-zinc-700 dark:text-zinc-300">{fmtPct(b.conversions, b.delivered)}</td>
                        <td className="px-3 py-2 text-right font-semibold text-amber-700 dark:text-amber-300">
                          {b.conversionValue > 0 ? fmtEuro(b.conversionValue) : '—'}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </Section>
          )}

          {/* ─── Top-Campaigns ─────────────────────────────────── */}
          {data.topCampaigns.length > 0 && (
            <Section title="Top-Performer (nach Conversion-Wert)">
              <div className="overflow-hidden rounded-lg border border-zinc-200 bg-white dark:border-zinc-700 dark:bg-zinc-900">
                <table className="w-full text-xs">
                  <thead className="border-b border-zinc-200 bg-zinc-50 text-left text-[11px] uppercase tracking-wider text-zinc-500 dark:border-zinc-700 dark:bg-zinc-800/50">
                    <tr>
                      <th className="px-3 py-2">Campaign</th>
                      <th className="px-3 py-2">Workspace</th>
                      <th className="px-3 py-2 text-right">Sent</th>
                      <th className="px-3 py-2 text-right">Verified</th>
                      <th className="px-3 py-2 text-right" title="Alle Open-Pixel (inkl. MPP)">Pixel</th>
                      <th className="px-3 py-2 text-right">Clicks</th>
                      <th className="px-3 py-2 text-right">Conversions</th>
                      <th className="px-3 py-2 text-right">Wert</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-zinc-100 dark:divide-zinc-800">
                    {data.topCampaigns.map((c) => (
                      <tr key={c.id}>
                        <td className="px-3 py-2 text-zinc-900 dark:text-zinc-100 max-w-[300px] truncate">{c.name}</td>
                        <td className="px-3 py-2 text-zinc-500 uppercase text-[10px]">{c.workspaceSlug}</td>
                        <td className="px-3 py-2 text-right text-zinc-700 dark:text-zinc-300">{c.sent.toLocaleString('de-DE')}</td>
                        <td className="px-3 py-2 text-right text-zinc-700 dark:text-zinc-300">{c.verifiedOpens.toLocaleString('de-DE')}</td>
                        <td className="px-3 py-2 text-right text-zinc-700 dark:text-zinc-300">{c.rawOpens.toLocaleString('de-DE')}</td>
                        <td className="px-3 py-2 text-right text-zinc-700 dark:text-zinc-300">{c.clicks.toLocaleString('de-DE')}</td>
                        <td className="px-3 py-2 text-right text-zinc-700 dark:text-zinc-300">{c.conversions.toLocaleString('de-DE')}</td>
                        <td className="px-3 py-2 text-right font-semibold text-amber-700 dark:text-amber-300">
                          {c.conversionValue > 0 ? fmtEuro(c.conversionValue) : '—'}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </Section>
          )}

          {/* ─── Hot Leads ──────────────────────────────────────── */}
          <Section title="Hot Leads jetzt (letzte 24h)">
            {data.hotLeads.length === 0 ? (
              <div className="rounded-md border border-dashed border-zinc-300 px-3 py-6 text-center text-[11px] text-zinc-500 dark:border-zinc-700">
                Noch keine Hot-Leads — Recipient muss geklickt UND ≥1 Onsite-Event ausgelöst haben.
              </div>
            ) : (
              <ul className="space-y-2">
                {data.hotLeads.map((h) => (
                  <li
                    key={h.recipientId}
                    className="flex items-center justify-between rounded-md border border-zinc-200 bg-white px-3 py-2 text-xs dark:border-zinc-700 dark:bg-zinc-900"
                  >
                    <div className="min-w-0 flex-1">
                      <div className="flex items-center gap-2">
                        <Flame className="h-3.5 w-3.5 shrink-0 text-orange-500" />
                        <span className="truncate font-medium text-zinc-900 dark:text-zinc-100">{fmtName(h)}</span>
                        <span className="rounded bg-zinc-100 px-1.5 py-0.5 text-[10px] uppercase text-zinc-600 dark:bg-zinc-800 dark:text-zinc-400">
                          {h.workspaceSlug}
                        </span>
                      </div>
                      <div className="ml-5.5 truncate text-[11px] text-zinc-500">
                        {h.email} · {h.campaignName}
                      </div>
                    </div>
                    <div className="ml-3 shrink-0 text-right">
                      <div className="text-[10px] text-zinc-400">geklickt {fmtTime(h.clickedAt)}</div>
                      <div className="text-[11px] font-semibold text-emerald-600 dark:text-emerald-400">
                        {h.behaviorCount} Onsite-Events
                      </div>
                    </div>
                  </li>
                ))}
              </ul>
            )}
          </Section>
        </>
      )}
    </div>
  );
}

function Section({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <div className="flex flex-col gap-2">
      <h2 className="text-xs font-semibold uppercase tracking-wider text-zinc-500">{title}</h2>
      {children}
    </div>
  );
}

function KpiTile({
  icon,
  label,
  value,
  sub,
  title,
}: {
  icon: React.ReactNode;
  label: string;
  value: string;
  sub: string;
  /** Native tooltip (z. B. KPI-Erklärung). */
  title?: string;
}) {
  return (
    <div
      className="flex flex-col gap-1 rounded-lg border border-zinc-200 bg-white p-3 dark:border-zinc-700 dark:bg-zinc-900"
      title={title}
    >
      <div className="flex items-center gap-1.5 text-[10px] uppercase tracking-wider text-zinc-500">
        {icon}
        {label}
      </div>
      <div className="text-lg font-semibold text-zinc-900 dark:text-zinc-100">{value}</div>
      <div className="text-[10px] text-zinc-400">{sub}</div>
    </div>
  );
}
