"use client";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { FileStack, LayoutTemplate, Plus } from "lucide-react";
import { Badge, Button, Card, Empty, Field, Input, PageHeader, Segmented, Sheet, Spinner, api, useAction } from "@/components/ui";
import { ago, useApi } from "@/components/hooks";

const NEW_FORM = { kind: "form", title: "Request a call-back", description: "", submitLabel: "Submit", successMessage: "Thanks! We’ll be in touch shortly.", createDeal: true, fields: [{ key: "name", label: "Full name", type: "text", required: true }, { key: "phone", label: "Mobile number", type: "phone", required: true }, { key: "email", label: "Email", type: "email" }], consent: [{ channel: "whatsapp", label: "Send me updates on WhatsApp" }] };
const NEW_PAGE = { kind: "page", title: "New landing page", theme: { accent: "#2563EB" }, blocks: [
  { id: "b1", type: "hero", props: { eyebrow: "New launch", title: "Your headline here", subtitle: "One sentence on why it matters.", cta: "Get details", image: "" } },
  { id: "b2", type: "features", props: { title: "Highlights", items: [{ title: "Location", text: "Describe it" }, { title: "Amenities", text: "Describe it" }, { title: "Payment plan", text: "Describe it" }] } },
  { id: "b3", type: "form", props: { title: "Get the brochure" } },
] };

export default function FormsPage() {
  const router = useRouter();
  const list = useApi<{ data: any[] }>("/forms");
  const [open, setOpen] = useState(false);
  const [type, setType] = useState<"form" | "page">("form");
  const [name, setName] = useState("");
  const { busy, run } = useAction();
  const create = () => run(async () => {
    const r = await api("/forms", { body: { name: name || (type === "form" ? "New form" : "New landing page"), type, schema: type === "form" ? NEW_FORM : NEW_PAGE, variants: [] } });
    router.push(`/forms/${r.data.id}`);
  });
  return (
    <>
      <PageHeader title="Forms & landing pages" subtitle="Hosted or embedded forms with UTM & click-ID capture, spam protection, pixels and A/B testing"
        actions={<Button variant="primary" icon={<Plus className="h-3.5 w-3.5" />} onClick={() => setOpen(true)}>Create</Button>} />
      <Card bodyClass="p-0">
        {list.loading && !list.data ? <div className="flex justify-center py-10"><Spinner /></div> : !list.data?.data.length ? <Empty title="No forms yet" icon={<FileStack className="h-5 w-5" />} action={<Button variant="primary" onClick={() => setOpen(true)}>Create a form</Button>} /> : (
          <table className="table-mac">
            <thead><tr><th>Name</th><th>Type</th><th>Status</th><th className="text-right">Views</th><th className="text-right">Submissions</th><th className="text-right">Conv. rate</th><th>Domain</th><th>Updated</th></tr></thead>
            <tbody>{list.data.data.map((f) => {
              const views = Object.values(f.stats ?? {}).reduce((s: number, x: any) => s + (x.views ?? 0), 0) as number;
              const subs = Object.values(f.stats ?? {}).reduce((s: number, x: any) => s + (x.submits ?? 0), 0) as number;
              return (
                <tr key={f.id} className="cursor-pointer" onClick={() => router.push(`/forms/${f.id}`)}>
                  <td className="font-medium"><span className="inline-flex items-center gap-2">{f.type === "page" ? <LayoutTemplate className="h-4 w-4 text-violet" /> : <FileStack className="h-4 w-4 text-brand" />}{f.name}</span></td>
                  <td><Badge tone={f.type === "page" ? "violet" : "red"}>{f.type}</Badge>{f.variants?.length > 1 && <Badge tone="amber" className="ml-1">A/B</Badge>}</td>
                  <td><Badge tone={f.status === "published" ? "green" : "gray"} dot>{f.status}</Badge></td>
                  <td className="text-right">{views.toLocaleString()}</td><td className="text-right">{Math.max(subs, f.submissions).toLocaleString()}</td><td className="text-right">{views ? `${((subs / views) * 100).toFixed(1)}%` : "—"}</td>
                  <td className="text-ink-3">{f.domain ?? "—"}</td><td className="text-ink-3">{ago(f.updatedAt)}</td>
                </tr>
              );
            })}</tbody>
          </table>
        )}
      </Card>
      <Sheet open={open} onClose={() => setOpen(false)} width={420} title="Create" footer={<><Button onClick={() => setOpen(false)}>Cancel</Button><Button variant="primary" loading={busy} onClick={create}>Create & edit</Button></>}>
        <div className="space-y-3">
          <Segmented value={type} onChange={setType} options={[{ value: "form", label: "Form" }, { value: "page", label: "Landing page" }]} />
          <Field label="Name"><Input autoFocus value={name} onChange={(e) => setName(e.target.value)} /></Field>
        </div>
      </Sheet>
    </>
  );
}
