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

const TEMPLATES: Record<string, { name: string; trigger: any; graph: any; goal?: any }> = {
  blank: { name: "Untitled journey", trigger: { type: "contact_created" }, graph: { nodes: [{ id: "t", type: "trigger", position: { x: 240, y: 0 }, data: { label: "Trigger" } }], edges: [] } },
  welcome: {
    name: "New lead welcome", trigger: { type: "contact_created" }, goal: { type: "stage_reached", value: "qualified" },
    graph: { nodes: [
      { id: "t", type: "trigger", position: { x: 240, y: 0 }, data: { label: "Contact created" } },
      { id: "a1", type: "action", position: { x: 240, y: 130 }, data: { label: "WhatsApp welcome", action: "send_message", channel: "whatsapp", body: "Hi {{first_name|there}}, thanks for your interest! Your advisor will call shortly." } },
      { id: "a2", type: "action", position: { x: 240, y: 260 }, data: { label: "Alert the owner", action: "notify_team", title: "New lead: {{name}}" } },
      { id: "g", type: "goal", position: { x: 240, y: 390 }, data: { label: "Done" } },
    ], edges: [{ id: "e1", source: "t", target: "a1" }, { id: "e2", source: "a1", target: "a2" }, { id: "e3", source: "a2", target: "g" }] },
  },
  reengage: {
    name: "Re-engage cold leads", trigger: { type: "tag_added", config: { tag: "cold" } }, goal: { type: "event_received", value: "message_received" },
    graph: { nodes: [
      { id: "t", type: "trigger", position: { x: 240, y: 0 }, data: { label: "Tag “cold” added" } },
      { id: "a1", type: "action", position: { x: 240, y: 130 }, data: { label: "Re-engage template", action: "send_message", channel: "whatsapp", body: "Hi {{first_name|there}}, still looking for a home? We have new offers at {{project|our projects}}." } },
      { id: "w", type: "wait", position: { x: 240, y: 260 }, data: { label: "Wait 3 days", days: 3 } },
      { id: "c", type: "condition", position: { x: 240, y: 390 }, data: { label: "Replied?", match: "all", rules: [{ field: "event:message_received", op: "within_days", value: 3 }] } },
      { id: "a2", type: "action", position: { x: 60, y: 530 }, data: { label: "Task for owner", action: "create_task", title: "Call back – re-engaged lead", dueInHours: 4 } },
      { id: "a3", type: "action", position: { x: 420, y: 530 }, data: { label: "Email brochure", action: "send_message", channel: "email", subject: "Your brochure", body: "Here is our latest brochure: https://example.com/brochure" } },
    ], edges: [{ id: "e1", source: "t", target: "a1" }, { id: "e2", source: "a1", target: "w" }, { id: "e3", source: "w", target: "c" }, { id: "e4", source: "c", target: "a2", sourceHandle: "yes", label: "Yes" }, { id: "e5", source: "c", target: "a3", sourceHandle: "no", label: "No" }] },
  },
  drip: {
    name: "Visit / appointment nurture drip", trigger: { type: "stage_changed", config: { stage: "site_visit" } }, goal: { type: "stage_reached", value: "negotiation" },
    graph: { nodes: [
      { id: "t", type: "trigger", position: { x: 240, y: 0 }, data: { label: "Stage → Visit / appointment" } },
      { id: "a1", type: "action", position: { x: 240, y: 130 }, data: { label: "Thank-you SMS", action: "send_message", channel: "sms", body: "ধন্যবাদ {{first_name|}}! আপনার সাইট ভিজিটের জন্য।" } },
      { id: "w1", type: "wait", position: { x: 240, y: 260 }, data: { label: "Wait 2 days", days: 2 } },
      { id: "s", type: "split", position: { x: 240, y: 390 }, data: { label: "A/B test", percent: 50 } },
      { id: "a2", type: "action", position: { x: 60, y: 530 }, data: { label: "Offer A: payment plan", action: "send_message", channel: "whatsapp", body: "Easy instalments available at {{project}}." } },
      { id: "a3", type: "action", position: { x: 420, y: 530 }, data: { label: "Offer B: loan support", action: "send_message", channel: "whatsapp", body: "Bank loan support up to 70% at {{project}}." } },
    ], edges: [{ id: "e1", source: "t", target: "a1" }, { id: "e2", source: "a1", target: "w1" }, { id: "e3", source: "w1", target: "s" }, { id: "e4", source: "s", target: "a2", sourceHandle: "a", label: "A" }, { id: "e5", source: "s", target: "a3", sourceHandle: "b", label: "B" }] },
  },
};

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

function Journeys() {
  const sp = useSearchParams();
  const router = useRouter();
  const list = useApi<{ data: any[] }>("/journeys");
  const [open, setOpen] = useState(false);
  useEffect(() => { if (sp.get("new") === "1") setOpen(true); }, [sp]);
  const [tpl, setTpl] = useState("welcome");
  const [name, setName] = useState("");
  const { busy, run } = useAction();
  const create = () => run(async () => {
    const t = TEMPLATES[tpl]!;
    const r = await api("/journeys", { body: { name: name || t.name, trigger: t.trigger, graph: t.graph, goal: t.goal ?? null } });
    router.push(`/journeys/${r.data.id}`);
  });
  return (
    <>
      <PageHeader title="Journeys" subtitle="Trigger → condition → action automations with versioning, goals, quiet hours and per-step analytics"
        actions={<Button variant="primary" icon={<Plus className="h-3.5 w-3.5" />} onClick={() => setOpen(true)}>New journey</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 journeys yet" icon={<Workflow className="h-5 w-5" />} action={<Button variant="primary" onClick={() => setOpen(true)}>Create from a template</Button>} /> : (
          <table className="table-mac">
            <thead><tr><th>Name</th><th>Trigger</th><th>Status</th><th>Version</th><th className="text-right">Active</th><th className="text-right">Completed</th><th className="text-right">Failed</th><th>Updated</th></tr></thead>
            <tbody>{list.data.data.map((j) => (
              <tr key={j.id} className="cursor-pointer" onClick={() => router.push(`/journeys/${j.id}`)}>
                <td className="font-medium">{j.name}</td>
                <td className="text-ink-2">{j.trigger.type.replace(/_/g, " ")}{j.trigger.config && Object.values(j.trigger.config).filter(Boolean).length ? ` · ${Object.values(j.trigger.config).filter((v) => typeof v === "string").join(", ")}` : ""}</td>
                <td><Badge tone={j.status === "live" ? "green" : j.status === "paused" ? "amber" : "gray"} dot>{j.status}</Badge></td>
                <td>{j.version ? `v${j.version}` : "—"}</td>
                <td className="text-right">{(j.runs.active ?? 0) + (j.runs.waiting ?? 0)}</td>
                <td className="text-right">{j.runs.completed ?? 0}</td>
                <td className="text-right">{j.runs.failed ?? 0}</td>
                <td className="text-ink-3">{ago(j.updatedAt)}</td>
              </tr>
            ))}</tbody>
          </table>
        )}
      </Card>
      <Sheet open={open} onClose={() => setOpen(false)} title="New journey" width={460} footer={<><Button onClick={() => setOpen(false)}>Cancel</Button><Button variant="primary" loading={busy} onClick={create}>Create & open canvas</Button></>}>
        <div className="space-y-3">
          <Field label="Start from"><Select value={tpl} onChange={(e) => setTpl(e.target.value)}><option value="welcome">New lead welcome</option><option value="reengage">Re-engage cold leads</option><option value="drip">Site-visit nurture drip (A/B)</option><option value="blank">Blank canvas</option></Select></Field>
          <Field label="Name"><Input value={name} onChange={(e) => setName(e.target.value)} placeholder={TEMPLATES[tpl]!.name} /></Field>
        </div>
      </Sheet>
    </>
  );
}

