"use client";

import { useState } from "react";
import { Avatar } from "@/components/ui/Avatar";
import { Icon } from "@/components/ui/Icon";
import { MiniChart } from "@/components/ui/MiniChart";
import { alertDialog } from "@/components/ui/Dialog";
import {
  addCreatorNoteAction,
  deleteCreatorNoteAction,
  refreshCreatorDataAction,
  changeStatusAction,
  toggleOnboardingItemAction,
  applyOnboardingTemplateAction,
} from "@/lib/creators/actions";
import {
  PLATFORM_META,
  STATUSES,
  statusMeta,
  fnum,
  labelOf,
  CATEGORIES,
  GAME_CATEGORIES,
  CONTENT_TYPES,
  CONTACT_METHODS,
  EVENT_META,
  type PlatformKey,
} from "@/lib/creators/constants";
import { scoreTone } from "@/lib/creators/score";
import type { CreatorDetail, CreatorNoteDTO, PlatformDTO, OnboardingItemDTO } from "@/lib/creators/queries";
import type { CreatorStatus } from "@prisma/client";

const TABS = [
  { key: "overview", label: "Übersicht", icon: "eye" },
  { key: "master", label: "Stammdaten", icon: "user" },
  { key: "analytics", label: "Analytics", icon: "activity" },
  { key: "onboarding", label: "Onboarding", icon: "check" },
  { key: "timeline", label: "Historie", icon: "clock" },
  { key: "notes", label: "Notizen", icon: "edit" },
] as const;
type TabKey = (typeof TABS)[number]["key"];

function fdate(iso: string | null): string {
  return iso ? new Date(iso).toLocaleDateString("de-DE", { day: "2-digit", month: "2-digit", year: "numeric" }) : "—";
}
function fdatetime(iso: string): string {
  return new Date(iso).toLocaleString("de-DE", { day: "2-digit", month: "2-digit", year: "2-digit", hour: "2-digit", minute: "2-digit" });
}
const pm = (p: string) => PLATFORM_META[p as PlatformKey];

function ScoreRing({ score, size = 66 }: { score: number; size?: number }) {
  const tone = scoreTone(score);
  const color = tone === "good" ? "#7ee787" : tone === "mid" ? "#ffc36b" : "#ff7a9c";
  const r = size / 2 - 5;
  const c = 2 * Math.PI * r;
  return (
    <div className="score-ring" style={{ width: size, height: size }}>
      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
        <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="rgba(255,255,255,.09)" strokeWidth={5} />
        <circle
          cx={size / 2} cy={size / 2} r={r} fill="none" stroke={color} strokeWidth={5} strokeLinecap="round"
          strokeDasharray={c} strokeDashoffset={c * (1 - score / 100)} transform={`rotate(-90 ${size / 2} ${size / 2})`}
        />
      </svg>
      <div className="score-ring-val" style={{ color }}>{score}</div>
    </div>
  );
}

function growthChip(abs: number | null, pct: number | null) {
  if (abs === null) return <span className="text-muted text-xs">—</span>;
  const cls = abs > 0 ? "grow-up" : abs < 0 ? "grow-down" : "";
  return (
    <span className={`grow ${cls}`}>
      {abs > 0 ? "+" : ""}{fnum(abs)}
      {pct !== null ? <em>{abs > 0 ? "+" : ""}{Math.round(pct)}%</em> : null}
    </span>
  );
}

export function CreatorProfile({
  creator,
  canManage,
  autoPlatforms,
  onClose,
  onEdit,
  onReload,
}: {
  creator: CreatorDetail;
  canManage: boolean;
  autoPlatforms: string[];
  onClose: () => void;
  onEdit: () => void;
  onReload: () => void;
}) {
  const [tab, setTab] = useState<TabKey>("overview");
  const [busy, setBusy] = useState(false);
  const [statusOpen, setStatusOpen] = useState(false);
  const sm = statusMeta(creator.status);

  const refresh = async () => {
    setBusy(true);
    const res = await refreshCreatorDataAction(creator.id);
    setBusy(false);
    if (res.error) return alertDialog({ title: "Fehler", message: res.error, danger: true });
    await onReload();
    await alertDialog({ title: "Daten aktualisiert", message: res.message || "Fertig." });
  };

  const setStatus = async (status: CreatorStatus) => {
    setStatusOpen(false);
    if (status === creator.status) return;
    setBusy(true);
    const res = await changeStatusAction(creator.id, status);
    setBusy(false);
    if (res.error) return alertDialog({ title: "Fehler", message: res.error, danger: true });
    onReload();
  };

  return (
    <div className="drawer-overlay" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
      <div className="drawer drawer-profile animate-in">
        <div className="mb-4 flex items-center justify-between">
          <span className="eyebrow">Creator-Profil</span>
          <button className="btn btn-ghost btn-sm" onClick={onClose} aria-label="Schließen"><Icon name="close" size={16} /></button>
        </div>

        {/* Kopf */}
        <div className="profile-head">
          <Avatar name={creator.stageName ?? creator.name} src={creator.avatarUrl} size={64} />
          <div className="min-w-0 flex-1">
            <div className="flex items-center gap-2">
              <span className="text-xl font-bold truncate">{creator.stageName ?? creator.name}</span>
              {creator.platformRows.some((p) => p.liveStatus) ? <span className="live-badge">● LIVE</span> : null}
            </div>
            {creator.stageName ? <div className="text-muted text-sm">{creator.name}</div> : null}
            <div className="mt-1.5 flex flex-wrap items-center gap-2">
              <div className="relative">
                <button className="status-badge" style={{ borderColor: `${sm.color}55` }} onClick={() => canManage && setStatusOpen((o) => !o)} disabled={!canManage || busy}>
                  <span className="status-badge-dot" style={{ background: sm.color }} />{sm.label}
                  {canManage ? <Icon name="chevron" size={12} style={{ transform: "rotate(90deg)" }} /> : null}
                </button>
                {statusOpen ? (
                  <div className="status-menu" onMouseLeave={() => setStatusOpen(false)}>
                    {STATUSES.map((s) => (
                      <button key={s.value} className="status-menu-item" data-active={s.value === creator.status} onClick={() => setStatus(s.value)}>
                        <span className="status-badge-dot" style={{ background: s.color }} />
                        <span className="flex-1 text-left">{s.label}</span>
                        <span className="text-muted" style={{ fontSize: 11 }}>{s.hint}</span>
                      </button>
                    ))}
                  </div>
                ) : null}
              </div>
              {creator.categoryLabel ? <span className="chip">{creator.categoryLabel}</span> : null}
              {creator.contentType ? <span className="chip">{labelOf(CONTENT_TYPES, creator.contentType)}</span> : null}
            </div>
          </div>
          <div className="flex flex-col items-center gap-1">
            <ScoreRing score={creator.score} />
            <span className="text-muted" style={{ fontSize: 10, letterSpacing: ".08em" }}>SCORE</span>
          </div>
        </div>

        {canManage ? (
          <div className="mb-1 mt-3 flex flex-wrap items-center gap-2">
            <button className="btn btn-ghost btn-sm" onClick={refresh} disabled={busy}><Icon name="trending" size={14} /> Daten aktualisieren</button>
            <button className="btn btn-primary btn-sm" onClick={onEdit}><Icon name="edit" size={14} /> Bearbeiten</button>
          </div>
        ) : null}

        {/* Tabs */}
        <div className="profile-tabs">
          {TABS.map((t) => (
            <button key={t.key} className="profile-tab" data-active={tab === t.key} onClick={() => setTab(t.key)}>
              <Icon name={t.icon} size={15} /> {t.label}
              {t.key === "onboarding" && creator.onboarding.length ? <span className="badge">{creator.onboarding.filter((o) => o.done).length}/{creator.onboarding.length}</span> : null}
            </button>
          ))}
        </div>

        <div className="profile-body">
          {tab === "overview" ? <OverviewTab creator={creator} /> : null}
          {tab === "master" ? <MasterTab creator={creator} /> : null}
          {tab === "analytics" ? <AnalyticsTab creator={creator} canManage={canManage} autoPlatforms={autoPlatforms} onRefresh={refresh} busy={busy} /> : null}
          {tab === "onboarding" ? <OnboardingTab creator={creator} canManage={canManage} onReload={onReload} /> : null}
          {tab === "timeline" ? <TimelineTab creator={creator} /> : null}
          {tab === "notes" ? <NotesTab creator={creator} canManage={canManage} /> : null}
        </div>
      </div>
    </div>
  );
}

// ── Übersicht ────────────────────────────────────────────────────────────

function OverviewTab({ creator }: { creator: CreatorDetail }) {
  const parts = creator.scoreParts;
  const bars = [
    { label: "Wachstum", v: parts.growth },
    { label: "Aktivität", v: parts.activity },
    { label: "Engagement", v: parts.engagement },
    { label: "Potenzial", v: parts.potential },
  ];
  return (
    <div className="flex flex-col gap-4">
      {creator.insights.length ? (
        <div className="flex flex-col gap-2">
          {creator.insights.map((ins, i) => (
            <div key={i} className={`insight insight-${ins.tone}`}>
              <Icon name={ins.kind === "warning" || ins.kind === "inactivity" ? "alert" : ins.kind === "recommendation" ? "target" : "trending"} size={16} />
              <span>{ins.text}</span>
            </div>
          ))}
        </div>
      ) : (
        <div className="insight insight-neutral"><Icon name="eye" size={16} /><span>Noch keine auffälligen Entwicklungen — weiter beobachten.</span></div>
      )}

      <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
        <div className="mini-tile"><span className="mini-tile-val">{fnum(creator.totalFollowers)}</span><span className="mini-tile-lbl">Reichweite</span></div>
        <div className="mini-tile"><span className="mini-tile-val">{creator.growthPct30 != null ? `${creator.growthPct30 > 0 ? "+" : ""}${Math.round(creator.growthPct30)}%` : "—"}</span><span className="mini-tile-lbl">30-Tage</span></div>
        <div className="mini-tile"><span className="mini-tile-val">{creator.daysSinceActivity != null ? `${creator.daysSinceActivity} T` : "—"}</span><span className="mini-tile-lbl">seit Aktivität</span></div>
        <div className="mini-tile"><span className="mini-tile-val">{creator.platformRows.length}</span><span className="mini-tile-lbl">Plattformen</span></div>
      </div>

      <div className="card-sub">
        <div className="label mb-2">Score-Zusammensetzung</div>
        <div className="flex flex-col gap-2">
          {bars.map((b) => (
            <div key={b.label} className="scorebar">
              <span className="scorebar-lbl">{b.label}</span>
              <div className="scorebar-track"><div className="scorebar-fill" style={{ width: `${Math.round(b.v)}%` }} /></div>
              <span className="scorebar-num">{Math.round(b.v)}</span>
            </div>
          ))}
        </div>
      </div>

      <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
        <FactRow icon="shield" label="Creator-Manager" value={creator.managerName ?? "—"} />
        <FactRow icon="users" label="Stellvertretung" value={creator.deputyName ?? "—"} />
        <FactRow icon="calendar" label="Wiedervorlage" value={fdate(creator.nextContactAt)} />
        <FactRow icon="target" label="Eintrittsdatum" value={fdate(creator.entryDate)} />
      </div>

      {creator.projects.length ? (
        <div className="field"><label className="label">Aktuelle Projekte</label><div className="flex flex-wrap gap-1.5">{creator.projects.map((p) => <span key={p.id} className="badge">{p.name}</span>)}</div></div>
      ) : null}
      {creator.notes ? <div className="field"><label className="label">Wichtige Hinweise</label><p className="text-sm">{creator.notes}</p></div> : null}
    </div>
  );
}

function FactRow({ icon, label, value }: { icon: string; label: string; value: string }) {
  return (
    <div className="fact-row">
      <span className="fact-icon"><Icon name={icon} size={15} /></span>
      <div className="min-w-0"><div className="fact-lbl">{label}</div><div className="fact-val truncate">{value}</div></div>
    </div>
  );
}

// ── Stammdaten ───────────────────────────────────────────────────────────

function MasterTab({ creator }: { creator: CreatorDetail }) {
  return (
    <div className="flex flex-col gap-4">
      <Section title="Persönliche Daten">
        <Field label="Vorname" value={creator.firstName} />
        <Field label="Nachname" value={creator.lastName} />
        <Field label="Künstlername" value={creator.stageName} />
        <Field label="Geburtsdatum" value={creator.birthDate ? `${fdate(creator.birthDate)}${creator.age != null ? ` (${creator.age} J.)` : ""}` : null} />
        <Field label="Land" value={creator.country} />
        <Field label="Sprache" value={creator.language} />
        <Field label="Zeitzone" value={creator.timezone} />
      </Section>
      <Section title="Kontakt">
        <Field label="Private E-Mail" value={creator.privateEmail} />
        <Field label="Avaria-E-Mail" value={creator.avariaEmail} />
        <Field label="Telefon" value={creator.phone} />
        <Field label="Discord" value={creator.discord} />
        <Field label="Bevorzugter Kontakt" value={creator.preferredContact} />
        <Field label="Kontaktmethode (Pipeline)" value={labelOf(CONTACT_METHODS, creator.contactMethod)} />
      </Section>
      <Section title="Einordnung & Avaria">
        <Field label="Status" value={statusMeta(creator.status).label} />
        <Field label="Hauptkategorie" value={creator.categoryLabel} />
        <Field label="Gaming-Bereich" value={labelOf(GAME_CATEGORIES, creator.gameCategory)} />
        <Field label="Content-Typ" value={labelOf(CONTENT_TYPES, creator.contentType)} />
        <Field label="Manager" value={creator.managerName} />
        <Field label="Stellvertretung" value={creator.deputyName} />
        <Field label="Kontaktaufnahme" value={fdate(creator.contactedAt)} />
        <Field label="Eintrittsdatum" value={fdate(creator.entryDate)} />
      </Section>
      {creator.status === "BLOCKED" && creator.blockedReason ? (
        <Section title="Sperrgrund"><div className="col-span-2 text-sm" style={{ color: "#ff9fb0" }}>{creator.blockedReason}</div></Section>
      ) : null}
    </div>
  );
}

function Section({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <div className="card-sub">
      <div className="label mb-2">{title}</div>
      <div className="grid grid-cols-2 gap-x-4 gap-y-2.5">{children}</div>
    </div>
  );
}
function Field({ label, value }: { label: string; value: string | null }) {
  return (
    <div className="min-w-0">
      <div className="fact-lbl">{label}</div>
      <div className="text-sm truncate" style={{ color: value ? "var(--text)" : "var(--muted)" }}>{value || "—"}</div>
    </div>
  );
}

// ── Analytics ────────────────────────────────────────────────────────────

function AnalyticsTab({ creator, canManage, autoPlatforms, onRefresh, busy }: { creator: CreatorDetail; canManage: boolean; autoPlatforms: string[]; onRefresh: () => void; busy: boolean }) {
  if (creator.platformRows.length === 0) {
    return <p className="text-muted text-sm">Keine Plattformen verbunden. Über „Bearbeiten" Social-Accounts hinzufügen — das Tracking startet sofort.</p>;
  }
  return (
    <div className="flex flex-col gap-3">
      {canManage ? (
        <div className="flex items-center justify-between">
          <span className="text-muted text-xs">Verlauf aus gespeicherten & abgerufenen Datenpunkten.</span>
          <button className="btn btn-ghost btn-sm" onClick={onRefresh} disabled={busy}><Icon name="trending" size={13} /> {busy ? "Abrufen …" : "Daten aktualisieren"}</button>
        </div>
      ) : null}
      {creator.platformRows.map((p) => <PlatformCard key={p.id} p={p} auto={autoPlatforms.includes(p.platform)} />)}
    </div>
  );
}

function PlatformCard({ p, auto }: { p: PlatformDTO; auto: boolean }) {
  const meta = pm(p.platform);
  const color = meta?.color ?? "#9ed7ff";
  return (
    <div className="analytics-card" style={{ ["--pc" as string]: color }}>
      <div className="flex items-center gap-2.5">
        <span className="platform-icon"><Icon name={p.platform} size={18} /></span>
        <div className="min-w-0 flex-1">
          <div className="flex items-center gap-2">
            <span className="font-bold">{meta?.label ?? p.platform}</span>
            {p.liveStatus ? <span className="live-badge">● LIVE</span> : null}
            {p.url ? <a href={p.url} target="_blank" rel="noreferrer" className="text-xs" style={{ color: "var(--blue)" }}>{p.handle ?? "Profil"}</a> : p.handle ? <span className="text-muted text-xs">{p.handle}</span> : null}
          </div>
          <div className="text-2xl font-black leading-tight">{fnum(p.followers)} <span className="text-muted text-xs font-normal">{meta?.followerLabel ?? "Follower"}</span></div>
        </div>
        <div className="platform-growth">
          <div><span className="platform-growth-lbl">Woche</span>{growthChip(p.growth.week, p.growthPct.week)}</div>
          <div><span className="platform-growth-lbl">Monat</span>{growthChip(p.growth.month, p.growthPct.month)}</div>
          <div><span className="platform-growth-lbl">Jahr</span>{growthChip(p.growth.year, p.growthPct.year)}</div>
        </div>
      </div>

      <MiniChart points={p.series.map((s) => s.v)} color={color} height={64} />

      {meta && meta.metrics.some((m) => p.metrics[m.key] != null) ? (
        <div className="metric-grid">
          {meta.metrics.filter((m) => p.metrics[m.key] != null).map((m) => (
            <div key={m.key} className="metric-tile"><span className="metric-val">{fnum(p.metrics[m.key])}</span><span className="metric-lbl">{m.label}</span></div>
          ))}
        </div>
      ) : null}
      <div className="sync-note" data-live={auto}>
        <Icon name={auto ? "activity" : "edit"} size={12} />
        {auto ? "Automatischer API-Abruf aktiv" : "Manuelle Pflege"}
        {p.lastSyncedAt ? <span className="text-muted"> · aktualisiert {fdatetime(p.lastSyncedAt)}</span> : null}
      </div>
    </div>
  );
}

// ── Onboarding ───────────────────────────────────────────────────────────

function OnboardingTab({ creator, canManage, onReload }: { creator: CreatorDetail; canManage: boolean; onReload: () => void }) {
  const [items, setItems] = useState<OnboardingItemDTO[]>(creator.onboarding);

  const toggle = async (id: string) => {
    if (!canManage) return;
    setItems((xs) => xs.map((x) => (x.id === id ? { ...x, done: !x.done } : x)));
    await toggleOnboardingItemAction(id);
    onReload();
  };
  const apply = async () => {
    await applyOnboardingTemplateAction(creator.id);
    onReload();
  };

  if (items.length === 0) {
    return (
      <div className="flex flex-col items-start gap-3">
        <p className="text-muted text-sm">Für diesen Creator wurde noch keine Onboarding-Checkliste angelegt. Sie wird automatisch erstellt, sobald der Status auf „Onboarding" wechselt.</p>
        {canManage ? <button className="btn btn-primary btn-sm" onClick={apply}><Icon name="plus" size={14} /> Standard-Checkliste anlegen</button> : null}
      </div>
    );
  }

  const done = items.filter((i) => i.done).length;
  const phases = [...new Set(items.map((i) => i.phase))];

  return (
    <div className="flex flex-col gap-4">
      <div>
        <div className="mb-1 flex items-center justify-between text-sm"><span className="font-bold">Fortschritt</span><span className="text-muted">{done}/{items.length}</span></div>
        <div className="progress-track"><div className="progress-fill" style={{ width: `${Math.round((done / items.length) * 100)}%`, background: "linear-gradient(90deg, #7ee787, #9ed7ff)" }} /></div>
      </div>
      {phases.map((ph) => (
        <div key={ph} className="card-sub">
          <div className="label mb-2">{ph}</div>
          <div className="flex flex-col gap-1">
            {items.filter((i) => i.phase === ph).map((i) => (
              <button key={i.id} className="check-row" data-done={i.done} onClick={() => toggle(i.id)} disabled={!canManage}>
                <span className="check-box">{i.done ? <Icon name="check" size={13} /> : null}</span>
                <span className="flex-1 text-left text-sm">{i.label}</span>
                {i.doneAt ? <span className="text-muted" style={{ fontSize: 11 }}>{fdate(i.doneAt)}</span> : null}
              </button>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}

// ── Historie ─────────────────────────────────────────────────────────────

function TimelineTab({ creator }: { creator: CreatorDetail }) {
  if (creator.events.length === 0) return <p className="text-muted text-sm">Noch keine Ereignisse dokumentiert.</p>;
  return (
    <div className="timeline">
      {creator.events.map((e) => {
        const m = EVENT_META[e.type] ?? EVENT_META.SYSTEM;
        return (
          <div key={e.id} className="timeline-row">
            <span className="timeline-dot" style={{ ["--ec" as string]: m.color }}><Icon name={m.icon} size={12} /></span>
            <div className="min-w-0 flex-1">
              <div className="flex items-center gap-2">
                <span className="text-sm font-semibold">{e.title}</span>
                <span className="text-muted" style={{ fontSize: 11 }}>{fdatetime(e.createdAt)}</span>
              </div>
              {e.body ? <div className="text-muted text-xs" style={{ wordBreak: "break-word" }}>{e.body}</div> : null}
              {e.authorName ? <div className="text-muted" style={{ fontSize: 10.5 }}>{e.authorName}</div> : null}
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ── Notizen ──────────────────────────────────────────────────────────────

function NotesTab({ creator, canManage }: { creator: CreatorDetail; canManage: boolean }) {
  const [notes, setNotes] = useState<CreatorNoteDTO[]>(creator.noteEntries);
  const [text, setText] = useState("");

  const add = async () => {
    if (!text.trim()) return;
    const res = await addCreatorNoteAction(creator.id, text);
    if (res.note) { setNotes((n) => [res.note!, ...n]); setText(""); }
  };
  const del = async (id: string) => { setNotes((n) => n.filter((x) => x.id !== id)); await deleteCreatorNoteAction(id); };

  return (
    <div className="flex flex-col gap-3">
      <div className="flex items-end gap-2">
        <textarea className="textarea" style={{ minHeight: 44 }} value={text} onChange={(e) => setText(e.target.value)} placeholder="Interne Notiz hinzufügen …" />
        <button className="btn btn-primary" onClick={add} disabled={!text.trim()}><Icon name="send" size={15} /></button>
      </div>
      {notes.length === 0 ? <p className="text-muted text-sm">Noch keine Notizen.</p> : (
        <div className="flex flex-col gap-2">
          {notes.map((n) => (
            <div key={n.id} className="note-row">
              <div className="min-w-0 flex-1">
                <div className="mb-0.5 flex items-center gap-2 text-xs"><span className="font-bold">{n.authorName}</span><span className="text-muted">{fdatetime(n.createdAt)}</span></div>
                <div className="text-sm" style={{ wordBreak: "break-word" }}>{n.body}</div>
              </div>
              {canManage ? <button className="comment-del" onClick={() => del(n.id)} aria-label="Löschen"><Icon name="trash" size={13} /></button> : null}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
