"use client";
/** Customisable dashboard: widgets rendered on the server, arranged here; each member saves their own order and visibility. */
import { useMemo, useState, type ReactNode } from "react";
import Link from "next/link";
import { ArrowDown, ArrowUp, Eye, EyeOff, LayoutGrid, RotateCcw, Search, SlidersHorizontal } from "lucide-react";
import { Badge, Button, Sheet, api, cx, useUI } from "./ui";
import { WIDGETS, type WidgetId } from "@/lib/dashboard";

export function DashboardGrid({ widgets, layout, defaults }: { widgets: Partial<Record<WidgetId, ReactNode>>; layout: { order: WidgetId[]; hidden: WidgetId[] }; defaults: { order: WidgetId[]; hidden: WidgetId[] } }) {
  const [order, setOrder] = useState(layout.order);
  const [hidden, setHidden] = useState(layout.hidden);
  const [open, setOpen] = useState(false);
  const [saving, setSaving] = useState(false);
  const { push } = useUI();
  const visible = order.filter((id) => !hidden.includes(id) && widgets[id]);

  const move = (id: WidgetId, dir: -1 | 1) => setOrder((o) => { const i = o.indexOf(id); const j = i + dir; if (j < 0 || j >= o.length) return o; const n = [...o]; [n[i], n[j]] = [n[j]!, n[i]!]; return n; });
  const toggle = (id: WidgetId) => setHidden((h) => (h.includes(id) ? h.filter((x) => x !== id) : [...h, id]));
  const save = async (next?: { order: WidgetId[]; hidden: WidgetId[] } | null) => {
    setSaving(true);
    try { await api("/me/dashboard", { method: "PUT", body: next === null ? { reset: true } : { order: next?.order ?? order, hidden: next?.hidden ?? hidden } }); push("ok", next === null ? "Dashboard reset to your industry default" : "Dashboard saved"); setOpen(false); }
    catch (e) { push("error", (e as Error).message); }
    setSaving(false);
  };

  return (
    <>
      <div className="mb-3 flex justify-end">
        <Button size="sm" icon={<SlidersHorizontal className="h-3.5 w-3.5" />} onClick={() => setOpen(true)}>Customize dashboard</Button>
      </div>
      <div className="grid grid-flow-row-dense grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-12">
        {visible.map((id) => <div key={id} className={cx("min-w-0 md:col-span-2", WIDGETS[id].span)}>{widgets[id]}</div>)}
      </div>
      {!visible.length && <div className="card grid place-items-center p-10 text-center text-[13px] text-ink-2"><LayoutGrid className="mb-2 h-6 w-6 text-ink-3" />All widgets are hidden. <button className="mt-2 text-brand underline" onClick={() => setOpen(true)}>Customize dashboard</button></div>}
      <Sheet open={open} onClose={() => setOpen(false)} title="Customize your dashboard" width={460}
        footer={<div className="flex gap-2"><Button icon={<RotateCcw className="h-3.5 w-3.5" />} onClick={() => { setOrder(defaults.order); setHidden(defaults.hidden); save(null); }}>Reset to industry default</Button><div className="flex-1" /><Button variant="primary" loading={saving} onClick={() => save()}>Save</Button></div>}>
        <p className="mb-3 text-[12.5px] text-ink-2">Show, hide and reorder widgets. This layout is just for you — teammates keep their own.</p>
        <ul className="space-y-1.5">
          {order.filter((id) => widgets[id]).map((id, i, arr) => (
            <li key={id} className={cx("flex items-center gap-2 rounded-[14px] border px-3 py-2", hidden.includes(id) ? "border-line/60 opacity-60" : "border-white/80 bg-white/60 dark:border-white/10 dark:bg-white/5")}>
              <button onClick={() => toggle(id)} className="text-ink-2 hover:text-brand" aria-label={hidden.includes(id) ? `Show ${WIDGETS[id].title}` : `Hide ${WIDGETS[id].title}`}>{hidden.includes(id) ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}</button>
              <div className="min-w-0 flex-1"><div className="text-[13px] font-semibold">{WIDGETS[id].title}</div><div className="truncate text-[11.5px] text-ink-3">{WIDGETS[id].description}</div></div>
              <button disabled={i === 0} onClick={() => move(id, -1)} className="rounded-[8px] p-1 text-ink-3 hover:bg-white hover:text-ink disabled:opacity-30" aria-label="Move up"><ArrowUp className="h-4 w-4" /></button>
              <button disabled={i === arr.length - 1} onClick={() => move(id, 1)} className="rounded-[8px] p-1 text-ink-3 hover:bg-white hover:text-ink disabled:opacity-30" aria-label="Move down"><ArrowDown className="h-4 w-4" /></button>
            </li>
          ))}
        </ul>
      </Sheet>
    </>
  );
}

export type DealRow = { id: string; ref: string; title: string; contact: string; contactId: string; value: string; stage: string; tone: string; updated: string };
export function RecentDeals({ rows }: { rows: DealRow[] }) {
  const [q, setQ] = useState("");
  const [status, setStatus] = useState("all");
  const filtered = useMemo(() => rows.filter((r) => (status === "all" || r.tone === status) && (!q || `${r.title} ${r.contact} ${r.ref}`.toLowerCase().includes(q.toLowerCase()))), [rows, q, status]);
  return (
    <section className="card h-full">
      <header className="flex flex-wrap items-center gap-2 px-5 pb-2 pt-4">
        <h3 className="font-display text-[15px] font-bold">Recent deals</h3>
        <div className="relative ml-auto"><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 deals" className="field h-8 w-[180px] rounded-full pl-8 text-[12.5px]" aria-label="Search deals" /></div>
        <select value={status} onChange={(e) => setStatus(e.target.value)} className="field h-8 w-auto rounded-full text-[12.5px]" aria-label="Filter"><option value="all">All</option><option value="green">Won</option><option value="blue">Open</option><option value="red">Lost</option></select>
      </header>
      <div className="overflow-x-auto px-2 pb-3">
        <table className="table-mac min-w-[560px]"><thead><tr><th>Deal ID</th><th>Deal</th><th>Contact</th><th className="text-right">Value</th><th>Status</th><th className="text-right">Updated</th></tr></thead>
          <tbody>{filtered.slice(0, 8).map((r) => (
            <tr key={r.id}><td className="font-mono text-[12px] text-ink-3">{r.ref}</td><td className="max-w-[220px] truncate font-medium"><Link href={`/pipeline?deal=${r.id}`} className="hover:text-brand">{r.title}</Link></td>
              <td className="max-w-[160px] truncate"><Link href={`/contacts/${r.contactId}`} className="hover:text-brand">{r.contact}</Link></td><td className="text-right font-semibold tabular-nums">{r.value}</td>
              <td><Badge tone={r.tone} dot>{r.stage}</Badge></td><td className="text-right text-ink-3">{r.updated}</td></tr>
          ))}</tbody></table>
        {!filtered.length && <p className="py-6 text-center text-[12.5px] text-ink-3">No deals match.</p>}
      </div>
    </section>
  );
}
