"use client";
import { useSearchParams } from "next/navigation";
import { Suspense, useState } from "react";
import { BrainCircuit, Copy, MessageSquareText, Sparkles, Wand2, Gauge, Lightbulb } from "lucide-react";
import { Badge, Button, Card, Empty, Field, Input, PageHeader, Segmented, Select, Spinner, Tabs, Textarea, api, useAction, useUI } from "@/components/ui";
import { money, useApi, useIndustry } from "@/components/hooks";
import { SimpleBars } from "@/components/charts";

export default function AIPage() {
  return <Suspense fallback={<Spinner />}><AI /></Suspense>;
}

function AI() {
  const sp = useSearchParams();
  const [tab, setTab] = useState(sp.get("tab") ?? "generate");
  const billing = useApi<{ data: { credits: { allowance: number; used: number; remaining: number } } }>("/billing");
  return (
    <>
      <PageHeader title="AI studio" subtitle="Works from your unified data · Bangla & English · anything touching spend goes through approvals"
        actions={billing.data && <Badge tone="violet">{billing.data.data.credits.remaining.toLocaleString()} / {billing.data.data.credits.allowance.toLocaleString()} AI credits left</Badge>} />
      <div className="mb-4"><Tabs value={tab} onChange={setTab} tabs={[{ value: "generate", label: "Generate" }, { value: "ask", label: "Ask your data" }, { value: "scoring", label: "Lead scoring" }, { value: "recs", label: "Recommendations" }]} /></div>
      {tab === "generate" && <Generate />}
      {tab === "ask" && <Ask />}
      {tab === "scoring" && <Scoring />}
      {tab === "recs" && <Recs />}
    </>
  );
}

function Generate() {
  const ind = useIndustry();
  const [f, setF] = useState({ kind: "ad_copy", brief: "", language: "en", variants: 3, tone: "" });
  const [out, setOut] = useState<{ variants: { title: string; content: string }[]; voice: string } | null>(null);
  const { busy, run } = useAction();
  const { push } = useUI();
  return (
    <div className="grid gap-4 lg:grid-cols-[380px_1fr]">
      <Card title={<span className="inline-flex items-center gap-1.5"><Wand2 className="h-4 w-4 text-violet" />Brief</span>}>
        <div className="space-y-3">
          <Field label="What to write"><Select value={f.kind} onChange={(e) => setF({ ...f, kind: e.target.value })}>
            <option value="ad_copy">Facebook / Instagram ad</option><option value="google_ad">Google responsive search ad</option><option value="caption">Social caption</option><option value="email">Email</option><option value="whatsapp">WhatsApp template</option><option value="sms">SMS</option><option value="landing">Landing page copy</option><option value="creative">Creative variation brief</option>
          </Select></Field>
          <Field label="Brief" hint="Product, audience, offer, proof points — the AI only uses claims you give it"><Textarea className="min-h-[140px]" value={f.brief} onChange={(e) => setF({ ...f, brief: e.target.value })} placeholder={ind.briefExample} /></Field>
          <div className="grid grid-cols-2 gap-3">
            <Field label="Language"><Segmented value={f.language} onChange={(v) => setF({ ...f, language: v })} options={[{ value: "en", label: "EN" }, { value: "bn", label: "বাংলা" }, { value: "both", label: "Both" }]} /></Field>
            <Field label="Variants"><Select value={String(f.variants)} onChange={(e) => setF({ ...f, variants: Number(e.target.value) })}>{[3, 4, 5, 6].map((n) => <option key={n}>{n}</option>)}</Select></Field>
          </div>
          <Field label="Tone (optional)"><Input value={f.tone} onChange={(e) => setF({ ...f, tone: e.target.value })} placeholder="Warm, premium, urgent…" /></Field>
          <Button variant="primary" className="w-full" icon={<Sparkles className="h-3.5 w-3.5" />} loading={busy} disabled={f.brief.trim().length < 5} onClick={() => run(async () => setOut((await api("/ai/generate", { body: f })).data))}>Generate</Button>
        </div>
      </Card>
      <div className="space-y-3">
        {!out && !busy && <Card><Empty title="Variants appear here" icon={<Sparkles className="h-5 w-5" />}>Uses your workspace brand voice from Settings or the brand kit.</Empty></Card>}
        {busy && <Card><div className="flex items-center justify-center gap-2 py-10 text-[13px] text-ink-3"><Spinner />Writing variants…</div></Card>}
        {out?.variants.map((v, i) => (
          <Card key={i} title={v.title || `Variant ${i + 1}`} actions={<Button size="sm" icon={<Copy className="h-3 w-3" />} onClick={() => { navigator.clipboard.writeText(v.content); push("ok", "Copied"); }}>Copy</Button>}>
            <p className="whitespace-pre-wrap text-[13.5px] leading-relaxed">{v.content}</p>
          </Card>
        ))}
        {out && <p className="text-[11.5px] text-ink-3">Brand voice used: {out.voice}</p>}
      </div>
    </div>
  );
}

const examples = (visits: string) => [`Which ad set brought the most ${visits.toLowerCase()} last month?`, "Cost per lead by campaign in the last 30 days", "Which rep won the most revenue this month?", "Leads per day last week", "Which source brought the most qualified leads?"];

function Ask() {
  const ind = useIndustry();
  const [q, setQ] = useState("");
  const [res, setRes] = useState<any>(null);
  const { busy, run } = useAction();
  const team = useApi<{ currency: string }>("/team");
  const cur = team.data?.currency ?? "BDT";
  const ask = (question: string) => { setQ(question); run(async () => setRes((await api("/ai/ask", { body: { question } })).data)); };
  const isMoney = res && ["revenue", "spend", "cpl"].includes(res.plan.metric);
  return (
    <div className="space-y-4">
      <div className="card flex items-center gap-2 p-2">
        <MessageSquareText className="ml-2 h-5 w-5 text-violet" />
        <input className="h-10 flex-1 bg-transparent text-[15px] outline-none placeholder:text-ink-3" placeholder="Ask a question about your marketing data…" value={q} onChange={(e) => setQ(e.target.value)} onKeyDown={(e) => e.key === "Enter" && q.trim() && ask(q)} />
        <Button variant="primary" loading={busy} disabled={!q.trim()} onClick={() => ask(q)}>Ask</Button>
      </div>
      <div className="flex flex-wrap gap-2">{examples(ind.visitPlural).map((e) => <button key={e} onClick={() => ask(e)} className="rounded-full border border-line bg-panel px-3 py-1 text-[12px] text-ink-2 hover:border-violet hover:text-violet">{e}</button>)}</div>
      {res && (
        <div className="grid gap-4 lg:grid-cols-[1fr_360px]">
          <Card title={res.answer}>
            {res.rows.length > 1 ? <SimpleBars data={res.rows.map((r: any) => ({ label: r.label, value: isMoney ? r.value / 100 : r.value }))} xKey="label" yKey="value" color="#7C6CF0" /> : res.rows.length === 1 ? <div className="py-6 text-center font-display text-[40px] font-bold">{isMoney ? money(res.rows[0].value, cur) : Math.round(res.rows[0].value * 100) / 100}</div> : <Empty title="No data for this question" />}
            <table className="table-mac mt-3"><tbody>{res.rows.map((r: any) => <tr key={r.label}><td>{r.label}</td><td className="text-right font-medium">{isMoney ? money(r.value, cur) : Math.round(r.value * 100) / 100}</td></tr>)}</tbody></table>
          </Card>
          <Card title="How this was answered">
            <dl className="space-y-2 text-[12.5px]">
              <div><dt className="label">Metric</dt><dd>{res.plan.metric} — {res.metricDefinition}</dd></div>
              <div><dt className="label">Date range</dt><dd>{res.plan.from} → {res.plan.to}</dd></div>
              <div><dt className="label">Grouped by</dt><dd>{res.plan.dimension}</dd></div>
              <div><dt className="label">Query</dt><dd><code className="block whitespace-pre-wrap rounded-[6px] bg-sunken p-2 font-mono text-[11px]">{res.query}</code></dd></div>
              <div><dt className="label">Interpreted by</dt><dd>{res.source === "ai" ? "AI query planner" : "Keyword rules (set ANTHROPIC_API_KEY for full AI)"}</dd></div>
            </dl>
          </Card>
        </div>
      )}
    </div>
  );
}

function Scoring() {
  const ind = useIndustry();
  const top = useApi<{ data: any[] }>("/contacts?limit=15&filter[min_score]=70");
  const { busy, run } = useAction();
  const [result, setResult] = useState<any>(null);
  return (
    <div className="grid gap-4 lg:grid-cols-[360px_1fr]">
      <Card title={<span className="inline-flex items-center gap-1.5"><Gauge className="h-4 w-4 text-violet" />Predictive lead scoring</span>}>
        <p className="text-[12.5px] text-ink-2">A per-workspace model trained on your won and lost deals scores every lead 0–100. It retrains weekly; until there is enough labelled history it uses a transparent heuristic.</p>
        <Button variant="primary" className="mt-4 w-full" icon={<BrainCircuit className="h-3.5 w-3.5" />} loading={busy} onClick={() => run(async () => { setResult((await api("/ai/score", { method: "POST" })).data); top.reload(); }, "Model retrained & leads rescored")}>Retrain now</Button>
        {result && <p className="mt-3 rounded-[8px] bg-sunken p-2.5 text-[12px]">{result.trained ? `Trained on ${result.samples} closed deals.` : `Not enough history yet (${result.samples}/${result.minimum} closed deals) — heuristic scores applied.`}</p>}
      </Card>
      <Card title="Hottest leads (score ≥ 70)" bodyClass="p-0">
        <table className="table-mac"><thead><tr><th>Lead</th><th>{ind.projectLabel}</th><th>Source</th><th className="text-right">Score</th></tr></thead>
          <tbody>{top.data?.data.map((c) => <tr key={c.id}><td><a className="font-medium hover:text-brand" href={`/contacts/${c.id}`}>{c.name}</a></td><td>{c.project ?? "—"}</td><td className="text-ink-3">{c.source}</td><td className="text-right"><Badge tone="green">{c.score}</Badge></td></tr>)}</tbody></table>
        {top.data && !top.data.data.length && <Empty title="No leads above 70 yet" />}
      </Card>
    </div>
  );
}

function Recs() {
  const recs = useApi<{ data: any[] }>("/ai/recommendations");
  const { push } = useUI();
  return (
    <Card title={<span className="inline-flex items-center gap-1.5"><Lightbulb className="h-4 w-4 text-violet" />Budget reallocation</span>} subtitle="Each recommendation shows its reasoning and expected impact · approving executes on the ad platform" bodyClass="p-0">
      {recs.loading && !recs.data ? <div className="flex justify-center py-10"><Spinner /></div> : !recs.data?.data.length ? <Empty title="No recommendations right now">Campaigns are performing within normal range.</Empty> : (
        <ul className="divide-y divide-line/60">{recs.data.data.map((r) => (
          <li key={r.campaignId} className="flex flex-wrap items-center gap-3 px-4 py-3">
            <Badge tone={r.action === "scale" ? "green" : r.action === "pause" ? "red" : "amber"}>{r.action} {r.action !== "pause" ? `${r.changePct > 0 ? "+" : ""}${r.changePct}%` : ""}</Badge>
            <div className="min-w-0 flex-1"><div className="text-[13px] font-medium">{r.name}</div><div className="text-[12px] text-ink-3">{r.reasoning}</div><div className="text-[12px] text-ink-2">Expected: {r.expectedImpact}</div></div>
            <Button size="sm" onClick={async () => { try { await api("/ai/actions", { body: { kind: r.action === "pause" ? "pause_ad" : "change_budget", proposed_action: { campaignId: r.campaignId, campaignName: r.name, provider: r.provider, changePct: r.changePct }, reasoning: r.reasoning, expected_impact: r.expectedImpact } }); push("ok", "Sent to approvals"); } catch (e) { push("error", (e as Error).message); } }}>Send to approvals</Button>
          </li>
        ))}</ul>
      )}
    </Card>
  );
}
