'use client';

/**
 * GA4-Session-Panel im RecipientTimelineDrawer (Phase 4).
 *
 * Lazy-fetched bei Click auf "Session anzeigen"-Button. Ohne Klick keine GA4-API-Calls
 * (schont Quota + Datenschutz: kein automatisches Tracking-für-Anschauen).
 *
 * Drei Render-States:
 *  - Initial: Button "GA4-Session laden"
 *  - Loading: Spinner
 *  - Result: Aggregat-Tiles + Top-Pages-Liste, oder "Keine Session gefunden"
 */

import { useState } from 'react';
import { BarChart3, Globe, Loader2, AlertTriangle, ChevronDown, ChevronUp } from 'lucide-react';

interface SessionSummary {
  sessions: number;
  pageviews: number;
  engagedSessions: number;
  averageEngagementDurationSec: number;
  conversions: number;
  topPages: Array<{ path: string; views: number }>;
}

interface Ga4Response {
  ok: boolean;
  configured?: boolean;
  utmContentMatch?: string;
  lookbackDays?: number;
  summary: SessionSummary | null;
  error?: string;
}

export interface Ga4SessionPanelProps {
  recipientId: string;
}

function fmtDuration(sec: number): string {
  if (sec < 60) return `${Math.round(sec)}s`;
  return `${Math.round(sec / 60)}m`;
}

export function Ga4SessionPanel({ recipientId }: Ga4SessionPanelProps) {
  const [data, setData] = useState<Ga4Response | null>(null);
  const [loading, setLoading] = useState(false);
  const [expanded, setExpanded] = useState(false);

  async function loadSession() {
    setLoading(true);
    try {
      const res = await fetch(`/api/recipients/${recipientId}/ga4-session`);
      const json = (await res.json()) as Ga4Response;
      setData(json);
      setExpanded(true);
    } catch (e) {
      setData({ ok: false, summary: null, error: e instanceof Error ? e.message : 'Netzwerk-Fehler' });
    } finally {
      setLoading(false);
    }
  }

  // Initial-Zustand: Button
  if (!data && !loading) {
    return (
      <div className="mt-6 rounded-md border border-zinc-200 p-3 dark:border-zinc-800">
        <button
          type="button"
          onClick={() => void loadSession()}
          className="inline-flex w-full items-center justify-center gap-2 rounded-md bg-zinc-50 px-3 py-2 text-xs font-medium text-zinc-700 transition hover:bg-zinc-100 dark:bg-zinc-900 dark:text-zinc-300 dark:hover:bg-zinc-800"
        >
          <BarChart3 className="h-3.5 w-3.5" />
          GA4-Session-Daten anzeigen
        </button>
        <p className="mt-1.5 text-[10px] text-zinc-400 text-center">
          On-demand Lookup via GA4 Data API. Pro Workspace konfigurierbar.
        </p>
      </div>
    );
  }

  // Loading
  if (loading) {
    return (
      <div className="mt-6 flex items-center justify-center rounded-md border border-zinc-200 p-3 text-xs text-zinc-500 dark:border-zinc-800">
        <Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" />
        Lade GA4-Session…
      </div>
    );
  }

  // Nicht konfiguriert
  if (data && data.configured === false) {
    return (
      <div className="mt-6 rounded-md border border-zinc-200 p-3 text-center text-[11px] text-zinc-500 dark:border-zinc-800">
        GA4 ist für diese Workspace nicht konfiguriert.
        <br />
        Settings → Onsite-Tracking → GA4-Property + Credentials hinterlegen.
      </div>
    );
  }

  // Fehler
  if (data && !data.ok) {
    return (
      <div className="mt-6 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>{data.error ?? 'GA4-Lookup fehlgeschlagen'}</span>
      </div>
    );
  }

  // Keine Session
  if (data && !data.summary) {
    return (
      <div className="mt-6 rounded-md border border-dashed border-zinc-300 p-3 text-center text-[11px] text-zinc-500 dark:border-zinc-700">
        Keine GA4-Session für diesen Empfänger gefunden
        <br />
        (Lookback {data.lookbackDays ?? 30} Tage).
        <br />
        Match-Key: <code className="rounded bg-zinc-100 px-1 dark:bg-zinc-800">{data.utmContentMatch}</code>
      </div>
    );
  }

  // Erfolg mit Daten
  const s = data!.summary!;
  return (
    <div className="mt-6 rounded-md border border-zinc-200 dark:border-zinc-800">
      <button
        type="button"
        onClick={() => setExpanded((v) => !v)}
        className="flex w-full items-center justify-between px-3 py-2 text-xs font-semibold text-zinc-700 dark:text-zinc-300"
      >
        <span className="flex items-center gap-1.5">
          <BarChart3 className="h-3.5 w-3.5" />
          GA4-Session ({s.sessions} {s.sessions === 1 ? 'Session' : 'Sessions'})
        </span>
        {expanded ? <ChevronUp className="h-3.5 w-3.5" /> : <ChevronDown className="h-3.5 w-3.5" />}
      </button>
      {expanded && (
        <div className="border-t border-zinc-200 px-3 py-3 dark:border-zinc-800">
          <div className="grid grid-cols-4 gap-2">
            <Stat label="Sessions" value={String(s.sessions)} />
            <Stat label="Pageviews" value={String(s.pageviews)} />
            <Stat label="Engagement" value={fmtDuration(s.averageEngagementDurationSec)} />
            <Stat label="Conversions" value={String(s.conversions)} />
          </div>
          {s.topPages.length > 0 && (
            <div className="mt-3">
              <div className="mb-1 flex items-center gap-1 text-[10px] uppercase tracking-wider text-zinc-500">
                <Globe className="h-3 w-3" /> Top-Pages
              </div>
              <ul className="space-y-1">
                {s.topPages.slice(0, 5).map((p, idx) => (
                  <li key={idx} className="flex items-center justify-between text-[11px]">
                    <span className="truncate text-zinc-700 dark:text-zinc-300" title={p.path}>{p.path}</span>
                    <span className="ml-2 shrink-0 tabular-nums text-zinc-500">{p.views}</span>
                  </li>
                ))}
              </ul>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

function Stat({ label, value }: { label: string; value: string }) {
  return (
    <div className="flex flex-col gap-0.5">
      <div className="text-[10px] uppercase tracking-wider text-zinc-500">{label}</div>
      <div className="text-sm font-semibold text-zinc-900 dark:text-zinc-100">{value}</div>
    </div>
  );
}
