"use client";
import { useState } from "react";
import { Copy, Download, FileBarChart, Mail, Plus, Trash2 } from "lucide-react";
import { Badge, Button, Card, Checkbox, Empty, Field, Input, PageHeader, Select, Sheet, Toggle, api, useAction, useUI } from "@/components/ui";
import { ago, useApi } from "@/components/hooks";

const SECTIONS = [["kpis", "Headline KPIs"], ["funnel", "Funnel & cost per stage"], ["attribution", "Source attribution"], ["campaigns", "Campaign performance"], ["reps", "Rep performance"], ["social", "Social engagement"]];
const MODELS = [["first_touch", "First touch"], ["last_touch", "Last touch"], ["linear", "Linear"], ["time_decay", "Time decay"], ["position_based", "Position based"]];

export default function ReportsPage() {
  const list = useApi<{ data: any[] }>("/reports/saved");
  const [edit, setEdit] = useState<any | "new" | null>(null);
  const { confirm, push } = useUI();
  return (
    <>
      <PageHeader title="Reports" subtitle="Save reports, schedule weekly or monthly PDF delivery and share white-label links with clients"
        actions={<Button variant="primary" icon={<Plus className="h-3.5 w-3.5" />} onClick={() => setEdit("new")}>New report</Button>} />
      <div className="grid gap-3 md:grid-cols-2 xl:grid-cols-3">
        {list.data?.data.map((r) => (
          <div key={r.id} className="card flex flex-col p-4">
            <div className="flex items-start gap-3">
              <span className="grid h-10 w-10 place-items-center rounded-[10px] bg-brand/10 text-brand"><FileBarChart className="h-5 w-5" /></span>
              <div className="min-w-0 flex-1"><div className="truncate font-semibold">{r.name}</div><div className="text-[12px] text-ink-3">Last {r.config.days ?? 30} days · {r.config.sections.length} sections{r.config.whiteLabel ? " · white-label" : ""}</div></div>
            </div>
            <div className="mt-3 flex flex-wrap gap-1.5">
              {r.schedule ? <Badge tone="violet">{r.schedule === "weekly_mon" ? "Every Monday" : "1st of month"}</Badge> : <Badge>Manual</Badge>}
              {r.recipients.map((e: string) => <Badge key={e} tone="gray">{e}</Badge>)}
            </div>
            <p className="mt-2 text-[11.5px] text-ink-3">{r.lastSentAt ? `Last sent ${ago(r.lastSentAt)}` : "Not sent yet"}</p>
            <div className="mt-3 flex flex-wrap gap-1.5 border-t border-line/60 pt-3">
              <a href={`/api/v1/reports/saved/${r.id}/pdf`} target="_blank" rel="noreferrer"><Button size="sm" icon={<Download className="h-3.5 w-3.5" />}>PDF</Button></a>
              <Button size="sm" icon={<Copy className="h-3.5 w-3.5" />} onClick={async () => { const t = await api(`/reports/saved/${r.id}/share`, { method: "POST" }); navigator.clipboard.writeText(`${location.origin}/r/${t.data.token}`); push("ok", "Client link copied"); }}>Share link</Button>
              <Button size="sm" icon={<Mail className="h-3.5 w-3.5" />} onClick={async () => { try { await api(`/reports/saved/${r.id}/send`, { method: "POST" }); push("ok", "Report emailed"); list.reload(); } catch (e) { push("error", (e as Error).message); } }}>Send now</Button>
              <Button size="sm" onClick={() => setEdit(r)}>Edit</Button>
              <Button size="sm" variant="ghost" aria-label="Delete" onClick={async () => { if (await confirm({ title: `Delete “${r.name}”?`, danger: true, confirmLabel: "Delete" })) { await api(`/reports/saved/${r.id}`, { method: "DELETE" }); list.reload(); } }}><Trash2 className="h-3.5 w-3.5" /></Button>
            </div>
          </div>
        ))}
      </div>
      {list.data && !list.data.data.length && <Card><Empty title="No saved reports" icon={<FileBarChart className="h-5 w-5" />} action={<Button variant="primary" onClick={() => setEdit("new")}>Build a report</Button>} /></Card>}
      {edit && <ReportSheet report={edit === "new" ? null : edit} onClose={() => setEdit(null)} onSaved={() => { setEdit(null); list.reload(); }} />}
    </>
  );
}

function ReportSheet({ report, onClose, onSaved }: { report: any | null; onClose: () => void; onSaved: () => void }) {
  const [f, setF] = useState({ name: report?.name ?? "Weekly client report", days: report?.config.days ?? 7, sections: (report?.config.sections ?? ["kpis", "funnel", "attribution", "campaigns"]) as string[], whiteLabel: !!report?.config.whiteLabel, model: report?.config.model ?? "", schedule: report?.schedule ?? "", recipients: (report?.recipients ?? []).join(", ") });
  const { busy, run } = useAction();
  const save = () => run(async () => {
    const body = { name: f.name, config: { days: Number(f.days), sections: f.sections, whiteLabel: f.whiteLabel, model: f.model || undefined }, schedule: f.schedule || null, recipients: f.recipients.split(",").map((x: string) => x.trim()).filter(Boolean) };
    if (report) await api(`/reports/saved/${report.id}`, { method: "PATCH", body }); else await api("/reports/saved", { body });
    onSaved();
  }, "Report saved");
  return (
    <Sheet open onClose={onClose} width={520} title={report ? "Edit report" : "New report"} footer={<><Button onClick={onClose}>Cancel</Button><Button variant="primary" loading={busy} onClick={save}>Save</Button></>}>
      <div className="space-y-3">
        <Field label="Name"><Input value={f.name} onChange={(e) => setF({ ...f, name: e.target.value })} /></Field>
        <div className="grid grid-cols-2 gap-3">
          <Field label="Period"><Select value={String(f.days)} onChange={(e) => setF({ ...f, days: Number(e.target.value) })}><option value="7">Last 7 days</option><option value="30">Last 30 days</option><option value="90">Last 90 days</option></Select></Field>
          <Field label="Attribution model"><Select value={f.model} onChange={(e) => setF({ ...f, model: e.target.value })}><option value="">Workspace default</option>{MODELS.map(([v, l]) => <option key={v} value={v}>{l}</option>)}</Select></Field>
        </div>
        <Field label="Sections"><div className="grid grid-cols-2 gap-2">{SECTIONS.map(([k, l]) => <Checkbox key={k} checked={f.sections.includes(k)} onChange={(v) => setF({ ...f, sections: v ? [...f.sections, k] : f.sections.filter((x) => x !== k) })} label={l} />)}</div></Field>
        <Toggle checked={f.whiteLabel} onChange={(v) => setF({ ...f, whiteLabel: v })} label="White-label (agency logo & colours, no platform branding)" />
        <div className="grid grid-cols-2 gap-3">
          <Field label="Email delivery"><Select value={f.schedule} onChange={(e) => setF({ ...f, schedule: e.target.value })}><option value="">Manual only</option><option value="weekly_mon">Every Monday</option><option value="monthly_1">1st of each month</option></Select></Field>
          <Field label="Recipients" hint="Comma separated"><Input value={f.recipients} onChange={(e) => setF({ ...f, recipients: e.target.value })} placeholder="client@company.com" /></Field>
        </div>
      </div>
    </Sheet>
  );
}
