"use client";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { Suspense, useEffect, useState } from "react";
import { Download, Phone, Plus, Search, Upload, UserPlus, Tag, Workflow, Trash2 } from "lucide-react";
import { Avatar, Badge, Button, Card, Checkbox, Empty, Field, Input, PageHeader, Select, Sheet, Spinner, api, useAction, useUI } from "@/components/ui";
import { SOURCE_LABEL, ago, useApi, useDebounced, useIndustry } from "@/components/hooks";

type Contact = { id: string; name: string; phones: string[]; emails: string[]; owner_id: string | null; lifecycle_stage: string; score: number | null; project: string | null; source: string | null; tags: string[]; created_at: string; city: string | null };

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

function Contacts() {
  const ind = useIndustry();
  const sp = useSearchParams();
  const router = useRouter();
  const [q, setQ] = useState("");
  const dq = useDebounced(q);
  const [filters, setFilters] = useState<Record<string, string>>(() => ({ ...(sp.get("filter") === "uncontacted" ? { uncontacted: "true" } : {}), ...(sp.get("segment") ? { segment: sp.get("segment")! } : {}) }));
  const [rows, setRows] = useState<Contact[]>([]);
  const [cursor, setCursor] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [sel, setSel] = useState<Set<string>>(new Set());
  const [newOpen, setNewOpen] = useState(sp.get("new") === "1");
  const [bulk, setBulk] = useState<null | "assign" | "tag" | "journey">(null);
  const team = useApi<{ data: { id: string; name: string; role: string }[]; perms: Record<string, string> }>("/team");
  const segs = useApi<{ data: { id: string; name: string; memberCount: number }[] }>("/segments");
  const { confirm, push } = useUI();
  const canEdit = team.data?.perms?.contacts === "C";

  const qs = (c?: string | null) => {
    const p = new URLSearchParams({ limit: "50" });
    if (dq) p.set("q", dq);
    Object.entries(filters).forEach(([k, v]) => v && p.set(`filter[${k}]`, v));
    if (c) p.set("cursor", c);
    return p.toString();
  };
  const load = async (append = false) => {
    setLoading(true);
    try {
      const r = await api<{ data: Contact[]; next_cursor: string | null }>(`/contacts?${qs(append ? cursor : null)}`);
      setRows((prev) => (append ? [...prev, ...r.data] : r.data));
      setCursor(r.next_cursor);
      if (!append) setSel(new Set());
    } catch (e) { push("error", (e as Error).message); } finally { setLoading(false); }
  };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  useEffect(() => { load(); }, [dq, JSON.stringify(filters)]);

  const owners = new Map((team.data?.data ?? []).map((u) => [u.id, u.name]));
  const toggle = (id: string) => setSel((s) => { const n = new Set(s); n.has(id) ? n.delete(id) : n.add(id); return n; });
  const setF = (k: string, v: string) => setFilters((f) => ({ ...f, [k]: v }));

  const exportCsv = () => {
    const head = ["name", "phone", "email", "project", "source", "stage", "score", "owner", "created_at"];
    const lines = rows.map((r) => [r.name, r.phones[0] ?? "", r.emails[0] ?? "", r.project ?? "", r.source ?? "", r.lifecycle_stage, r.score ?? "", owners.get(r.owner_id ?? "") ?? "", r.created_at].map((v) => `"${String(v).replace(/"/g, '""')}"`).join(","));
    const blob = new Blob([[head.join(","), ...lines].join("\n")], { type: "text/csv" });
    const a = document.createElement("a"); a.href = URL.createObjectURL(blob); a.download = "contacts.csv"; a.click();
  };

  return (
    <>
      <PageHeader title="Contacts" subtitle="One profile per person across ads, forms, chats, calls and sales"
        actions={<>
          <Button icon={<Download className="h-3.5 w-3.5" />} onClick={exportCsv} disabled={!rows.length}>Export</Button>
          {canEdit && <Link href="/contacts/import"><Button icon={<Upload className="h-3.5 w-3.5" />}>Import</Button></Link>}
          <Button variant="primary" icon={<Plus className="h-3.5 w-3.5" />} onClick={() => setNewOpen(true)}>New lead</Button>
        </>} />

      <Card bodyClass="p-0">
        <div className="flex flex-wrap items-center gap-2 border-b border-line/70 p-3">
          <div className="relative min-w-[220px] flex-1">
            <Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-ink-3" />
            <Input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search name, phone or email" className="pl-8" />
          </div>
          <Select value={filters.lifecycle_stage ?? ""} onChange={(e) => setF("lifecycle_stage", e.target.value)} className="w-[140px]">
            <option value="">All stages</option><option value="lead">Lead</option><option value="opportunity">Opportunity</option><option value="customer">Customer</option><option value="lost">Lost</option>
          </Select>
          <Select value={filters.source ?? ""} onChange={(e) => setF("source", e.target.value)} className="w-[150px]">
            <option value="">All sources</option>{Object.entries(SOURCE_LABEL).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
          </Select>
          {team.data?.perms?.contacts === "C" && (
            <Select value={filters.owner_id ?? ""} onChange={(e) => setF("owner_id", e.target.value)} className="w-[150px]">
              <option value="">All owners</option><option value="none">Unassigned</option>{team.data?.data.map((u) => <option key={u.id} value={u.id}>{u.name}</option>)}
            </Select>
          )}
          <Select value={filters.segment ?? ""} onChange={(e) => setF("segment", e.target.value)} className="w-[170px]">
            <option value="">All segments</option>{segs.data?.data.map((s) => <option key={s.id} value={s.id}>{s.name} ({s.memberCount})</option>)}
          </Select>
          <Checkbox checked={filters.uncontacted === "true"} onChange={(v) => setF("uncontacted", v ? "true" : "")} label="Not contacted" />
        </div>

        {sel.size > 0 && (
          <div className="flex flex-wrap items-center gap-2 border-b border-line/70 bg-brand/5 px-3 py-2 text-[12.5px]">
            <b>{sel.size} selected</b>
            {canEdit && <Button size="sm" icon={<UserPlus className="h-3.5 w-3.5" />} onClick={() => setBulk("assign")}>Assign</Button>}
            <Button size="sm" icon={<Tag className="h-3.5 w-3.5" />} onClick={() => setBulk("tag")}>Add tag</Button>
            <Button size="sm" icon={<Workflow className="h-3.5 w-3.5" />} onClick={() => setBulk("journey")}>Enroll in journey</Button>
            {canEdit && <Button size="sm" variant="ghost" className="text-bad" icon={<Trash2 className="h-3.5 w-3.5" />} onClick={async () => {
              if (!(await confirm({ title: `Permanently delete ${sel.size} contact(s)?`, body: "This hard-deletes the contacts and everything linked to them across all modules. It cannot be undone.", danger: true, confirmLabel: "Delete" }))) return;
              for (const id of sel) await api(`/contacts/${id}`, { method: "DELETE" }).catch(() => {});
              push("ok", "Deleted"); load();
            }}>Delete</Button>}
            <button className="ml-auto text-ink-3 hover:text-ink" onClick={() => setSel(new Set())}>Clear</button>
          </div>
        )}

        <ul className="divide-y divide-line/60 md:hidden">
          {rows.map((r) => (
            <li key={r.id}>
              <Link href={`/contacts/${r.id}`} className="flex items-center gap-3 px-3 py-3 active:bg-sunken">
                <Avatar name={r.name} size={36} />
                <div className="min-w-0 flex-1">
                  <div className="flex items-center gap-2"><span className="truncate font-medium">{r.name}</span>{r.score != null && <Badge tone={r.score >= 70 ? "green" : r.score >= 40 ? "amber" : "gray"}>{r.score}</Badge>}</div>
                  <div className="truncate text-[12px] text-ink-3">{[r.phones[0], r.project].filter(Boolean).join(" · ")}</div>
                  <div className="truncate text-[11.5px] text-ink-3">{owners.get(r.owner_id ?? "") ?? "Unassigned"} · {ago(r.created_at)}</div>
                </div>
                {r.phones[0] && <button type="button" onClick={(e) => { e.preventDefault(); e.stopPropagation(); window.location.href = `tel:${r.phones[0]}`; }} className="grid h-9 w-9 place-items-center rounded-full bg-brand/10 text-brand" aria-label={`Call ${r.name}`}><Phone className="h-4 w-4" /></button>}
              </Link>
            </li>
          ))}
        </ul>
        <div className="hidden overflow-x-auto md:block">
          <table className="table-mac min-w-[860px]">
            <thead><tr>
              <th className="w-8"><Checkbox checked={rows.length > 0 && sel.size === rows.length} onChange={(v) => setSel(v ? new Set(rows.map((r) => r.id)) : new Set())} /></th>
              <th>Name</th><th>Phone / email</th><th>{ind.projectLabel}</th><th>Source</th><th>Stage</th><th>Score</th><th>Owner</th><th className="text-right">Created</th>
            </tr></thead>
            <tbody>
              {rows.map((r) => (
                <tr key={r.id} className="cursor-pointer" onClick={() => router.push(`/contacts/${r.id}`)}>
                  <td onClick={(e) => e.stopPropagation()}><Checkbox checked={sel.has(r.id)} onChange={() => toggle(r.id)} /></td>
                  <td><div className="flex items-center gap-2.5"><Avatar name={r.name} size={26} /><div className="min-w-0"><div className="truncate font-medium">{r.name}</div>{r.tags.length > 0 && <div className="truncate text-[11px] text-ink-3">{r.tags.slice(0, 3).join(" · ")}</div>}</div></div></td>
                  <td className="text-ink-2"><div>{r.phones[0] ?? "—"}</div><div className="text-[11.5px] text-ink-3">{r.emails[0] ?? ""}</div></td>
                  <td>{r.project ?? <span className="text-ink-3">—</span>}</td>
                  <td>{r.source ? <Badge>{SOURCE_LABEL[r.source] ?? r.source}</Badge> : "—"}</td>
                  <td><Badge tone={r.lifecycle_stage === "customer" ? "green" : r.lifecycle_stage === "lost" ? "gray" : r.lifecycle_stage === "opportunity" ? "violet" : "blue"}>{r.lifecycle_stage}</Badge></td>
                  <td>{r.score != null ? <Badge tone={r.score >= 70 ? "green" : r.score >= 40 ? "amber" : "gray"}>{r.score}</Badge> : "—"}</td>
                  <td className="text-ink-2">{owners.get(r.owner_id ?? "") ?? <span className="text-ink-3">Unassigned</span>}</td>
                  <td className="text-right text-ink-3">{ago(r.created_at)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div>
          {loading && <div className="flex justify-center py-6"><Spinner /></div>}
          {!loading && !rows.length && <Empty title="No contacts match" icon={<Search className="h-5 w-5" />}>Try a different search or clear the filters.</Empty>}
          {cursor && !loading && <div className="flex justify-center border-t border-line/70 py-3"><Button onClick={() => load(true)}>Load more</Button></div>}
        </div>
      </Card>

      <NewLeadSheet open={newOpen} onClose={() => setNewOpen(false)} team={team.data?.data ?? []} canAssign={canEdit} onCreated={(id) => router.push(`/contacts/${id}`)} />
      <BulkSheet mode={bulk} ids={[...sel]} team={team.data?.data ?? []} onClose={() => setBulk(null)} onDone={() => { setBulk(null); load(); }} />
    </>
  );
}

function NewLeadSheet({ open, onClose, team, canAssign, onCreated }: { open: boolean; onClose: () => void; team: { id: string; name: string }[]; canAssign: boolean; onCreated: (id: string) => void }) {
  const ind = useIndustry();
  const [f, setF] = useState({ name: "", phone: "", email: "", project: "", city: "", channel: "manual", owner_id: "", note: "", value: "" });
  const { busy, run } = useAction();
  const set = (k: keyof typeof f) => (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => setF({ ...f, [k]: e.target.value });
  const submit = () => run(async () => {
    if (!f.phone && !f.email) throw new Error("Add a phone number or email");
    const r = await api("/leads", { body: { name: f.name || undefined, phone: f.phone || undefined, email: f.email || undefined, project: f.project || undefined, city: f.city || undefined, owner_id: f.owner_id || undefined, note: f.note || undefined, value: f.value ? Math.round(Number(f.value) * 100) : undefined, attribution: { channel: f.channel } }, idempotent: true });
    onClose();
    onCreated(r.data.contact.id);
  }, "Lead saved");
  return (
    <Sheet open={open} onClose={onClose} title="New lead" footer={<><Button onClick={onClose}>Cancel</Button><Button variant="primary" loading={busy} onClick={submit}>Save lead</Button></>}>
      <div className="grid grid-cols-2 gap-3">
        <Field label="Full name" className="col-span-2"><Input autoFocus value={f.name} onChange={set("name")} /></Field>
        <Field label="Mobile" hint="Any format — normalised to +880…"><Input value={f.phone} onChange={set("phone")} placeholder="01712 345678" /></Field>
        <Field label="Email"><Input type="email" value={f.email} onChange={set("email")} /></Field>
        <Field label={ind.projectLabel}><Input value={f.project} onChange={set("project")} placeholder={`Which ${ind.projectLabel.toLowerCase()} are they interested in?`} /></Field>
        <Field label="City"><Input value={f.city} onChange={set("city")} /></Field>
        <Field label="Source"><Select value={f.channel} onChange={set("channel")}><option value="manual">Manual entry</option><option value="call">Inbound call</option><option value="walk_in">Walk-in</option><option value="referral">Referral</option><option value="event">Event</option></Select></Field>
        {canAssign ? <Field label="Owner" hint="Leave empty to use routing rules"><Select value={f.owner_id} onChange={set("owner_id")}><option value="">Auto-route</option>{team.map((u) => <option key={u.id} value={u.id}>{u.name}</option>)}</Select></Field> : <div />}
        <Field label="Expected value" hint="Optional, in workspace currency"><Input type="number" min="0" value={f.value} onChange={set("value")} /></Field>
        <Field label="Note" className="col-span-2"><textarea className="field min-h-[60px]" value={f.note} onChange={set("note")} /></Field>
      </div>
      <p className="mt-3 text-[11.5px] text-ink-3">Existing contacts with the same phone or email are updated instead of duplicated.</p>
    </Sheet>
  );
}

function BulkSheet({ mode, ids, team, onClose, onDone }: { mode: null | "assign" | "tag" | "journey"; ids: string[]; team: { id: string; name: string }[]; onClose: () => void; onDone: () => void }) {
  const [v, setV] = useState("");
  const journeys = useApi<{ data: { id: string; name: string; status: string }[] }>(mode === "journey" ? "/journeys" : null, [mode]);
  const { busy, run } = useAction();
  useEffect(() => setV(""), [mode]);
  const apply = () => run(async () => {
    if (!v) throw new Error("Choose a value");
    if (mode === "journey") {
      const r = await api(`/journeys/${v}/enroll`, { body: { contact_ids: ids } });
      onDone();
      return r;
    }
    for (const id of ids) {
      if (mode === "assign") await api(`/contacts/${id}`, { method: "PATCH", body: { owner_id: v } });
      else {
        const c = await api(`/contacts/${id}`);
        await api(`/contacts/${id}`, { method: "PATCH", body: { tags: [...new Set([...c.data.tags, ...v.split(",").map((t: string) => t.trim()).filter(Boolean)])] } });
      }
    }
    onDone();
  }, "Done");
  return (
    <Sheet open={!!mode} onClose={onClose} title={mode === "assign" ? `Assign ${ids.length} contact(s)` : mode === "tag" ? `Tag ${ids.length} contact(s)` : `Enroll ${ids.length} contact(s)`} width={420}
      footer={<><Button onClick={onClose}>Cancel</Button><Button variant="primary" loading={busy} onClick={apply}>Apply</Button></>}>
      {mode === "assign" && <Field label="Owner"><Select value={v} onChange={(e) => setV(e.target.value)}><option value="">Choose…</option>{team.map((u) => <option key={u.id} value={u.id}>{u.name}</option>)}</Select></Field>}
      {mode === "tag" && <Field label="Tags" hint="Comma separated"><Input value={v} onChange={(e) => setV(e.target.value)} placeholder="vip, nrb" /></Field>}
      {mode === "journey" && <Field label="Live journey"><Select value={v} onChange={(e) => setV(e.target.value)}><option value="">Choose…</option>{journeys.data?.data.filter((j) => j.status === "live").map((j) => <option key={j.id} value={j.id}>{j.name}</option>)}</Select></Field>}
    </Sheet>
  );
}
