"use client";

// ============================================================
// Lead Verification — the verification desk.
//   · Stat tiles : Verified / In Progress / Assigned / Pending
//                  / Unverified counts (click to filter)
//   · Toolbar    : search + status / source / assignee filters
//   · Table      : Lead ID · Customer · Phone · Source ·
//                  Assigned To · Status · Verification · Created
//                  · Actions (view / verify / ⋯ menu)
//   · Detail     : view → popup with Contact, Assignment,
//                  Verification Notes and an Activity timeline
// Data comes from verify-data.ts (client-side mock).
// ============================================================

import { useMemo, useState, useEffect } from "react";
import { createPortal } from "react-dom";
import { Avatar, Btn, Icon, Modal, PageHead, Pill, useToast } from "./ui";
import { V_LEADS, V_STATUS_META, V_SOURCES, V_ASSIGNEES, type VStatus, type VLead, type VActivity } from "./verify-data";

const STAT_ORDER: VStatus[] = ["verified", "in_progress", "assigned", "pending", "unverified"];
const STAT_ICON: Record<VStatus, string> = {
  verified: "check-circle", in_progress: "refresh", assigned: "user", pending: "clock", unverified: "alert",
};

/* ---- derive detail when the row doesn't carry it ---------- */
function deriveEmail(l: VLead) {
  if (l.email) return l.email;
  const [first, ...rest] = l.name.toLowerCase().split(" ");
  return `${first}.${rest.join("")}@gmail.com`;
}
function deriveCreatedAt(l: VLead) { return l.createdAt ?? `${l.created}, 10:00 AM`; }
function buildActivity(l: VLead): VActivity[] {
  if (l.activity) return l.activity;
  const who = l.assignee?.name ?? "System";
  const a: VActivity[] = [{ text: `Lead submitted via ${l.source.toLowerCase()} intake.`, time: deriveCreatedAt(l), who: "System" }];
  if (l.assignee) a.push({ text: `Assigned to ${l.assignee.name}.`, time: l.created, who: l.assignee.name });
  if (l.status === "in_progress") a.push({ text: `Verification in progress — ${l.verification.toLowerCase()}.`, time: l.created, who });
  if (l.status === "verified") a.push({ text: "Verified and pushed to New Leads.", time: l.verifiedAt ?? l.created, who });
  return a;
}

type MenuState = { lead: VLead; x: number; y: number } | null;

export function Verify() {
  const toast = useToast();
  const [query, setQuery] = useState("");
  const [status, setStatus] = useState("all");
  const [source, setSource] = useState("all");
  const [assignee, setAssignee] = useState("all");
  const [selected, setSelected] = useState<VLead | null>(null);
  const [menu, setMenu] = useState<MenuState>(null);

  const counts = useMemo(() => {
    const m: Record<string, number> = {};
    for (const l of V_LEADS) m[l.status] = (m[l.status] ?? 0) + 1;
    return m;
  }, []);

  const rows = useMemo(() => {
    const q = query.trim().toLowerCase();
    return V_LEADS.filter((l) => {
      const matchQ = !q || `${l.name} ${l.id} ${l.phone} ${l.source} ${l.address}`.toLowerCase().includes(q);
      const matchStatus = status === "all" || l.status === status;
      const matchSource = source === "all" || l.source === source;
      const matchAssignee = assignee === "all" || l.assignee?.name === assignee;
      return matchQ && matchStatus && matchSource && matchAssignee;
    });
  }, [query, status, source, assignee]);

  function act(l: VLead, title: string, desc: string, tone: "success" | "info" = "info") {
    setMenu(null);
    toast.push({ tone, title, desc });
  }

  return (
    <div className="view lv">
      <PageHead
        eyebrow="Sales"
        title="Lead Verification"
        subtitle="Identity & insurance checks before a lead becomes a working deal."
        icon="verify"
        actions={<Btn variant="outline" icon="refresh" onClick={() => toast.push({ tone: "info", title: "Queue refreshed", desc: "Verification queue is up to date." })}>Refresh</Btn>}
      />

      {/* ---- stat tiles ---- */}
      <div className="lv-stats">
        {STAT_ORDER.map((s) => {
          const meta = V_STATUS_META[s];
          return (
            <button key={s} className={`lv-stat tone-${meta.tone} ${status === s ? "active" : ""}`} onClick={() => setStatus(status === s ? "all" : s)}>
              <span className="lv-stat-ic"><Icon name={STAT_ICON[s]} size={16} /></span>
              <span className="lv-stat-val">{counts[s] ?? 0}</span>
              <span className="lv-stat-lbl">{meta.label}</span>
            </button>
          );
        })}
      </div>

      {/* ---- toolbar ---- */}
      <div className="lv-toolbar">
        <div className="lv-search">
          <Icon name="search" size={16} />
          <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search name, lead ID, phone, source…" aria-label="Search verification leads" />
          {query && <button className="lv-search-x" aria-label="Clear" onClick={() => setQuery("")}><Icon name="x" size={14} /></button>}
        </div>
        <select className="ds-select lv-filter" value={status} onChange={(e) => setStatus(e.target.value)} aria-label="Filter by status">
          <option value="all">All statuses</option>
          {STAT_ORDER.map((s) => <option key={s} value={s}>{V_STATUS_META[s].label}</option>)}
        </select>
        <select className="ds-select lv-filter" value={source} onChange={(e) => setSource(e.target.value)} aria-label="Filter by source">
          <option value="all">All sources</option>
          {V_SOURCES.map((s) => <option key={s} value={s}>{s}</option>)}
        </select>
        <select className="ds-select lv-filter" value={assignee} onChange={(e) => setAssignee(e.target.value)} aria-label="Filter by assignee">
          <option value="all">All assignees</option>
          {V_ASSIGNEES.map((a) => <option key={a} value={a}>{a}</option>)}
        </select>
      </div>

      {/* ---- table ---- */}
      <div className="lv-tablewrap">
        <table className="lv-table">
          <thead>
            <tr>
              <th>Lead ID</th><th>Customer</th><th>Phone</th><th>Source</th>
              <th>Assigned To</th><th>Status</th><th>Verification</th><th>Created</th>
              <th className="lv-actions-h">Actions</th>
            </tr>
          </thead>
          <tbody>
            {rows.length === 0 ? (
              <tr><td colSpan={9} className="lv-empty">No leads match your filters.</td></tr>
            ) : rows.map((l) => {
              const meta = V_STATUS_META[l.status];
              return (
                <tr key={l.id}>
                  <td><div className="lv-id">{l.id}</div><div className="lv-id-date">{l.created}</div></td>
                  <td>
                    <div className="lv-cust">
                      <Avatar initials={l.initials} size={34} />
                      <div className="lv-cust-body">
                        <div className="lv-cust-name">{l.name}</div>
                        <div className="lv-cust-addr">{l.address}</div>
                      </div>
                    </div>
                  </td>
                  <td className="lv-phone">{l.phone}</td>
                  <td><span className="lv-source">{l.source}</span></td>
                  <td>
                    {l.assignee ? (
                      <div className="lv-assignee">
                        <Avatar initials={l.assignee.initials} size={26} gradient="linear-gradient(135deg,#4f8cff,#2c5cff)" />
                        <span>{l.assignee.name}</span>
                      </div>
                    ) : <span className="lv-unassigned">— Unassigned</span>}
                  </td>
                  <td><Pill tone={meta.tone}>{meta.label}</Pill></td>
                  <td><span className={`lv-verif v-${l.status}`}><Icon name={STAT_ICON[l.status]} size={13} /> {l.verification}</span></td>
                  <td className="lv-created">{l.created}</td>
                  <td>
                    <div className="lv-rowacts">
                      <button className="lv-act" aria-label="View details" title="View details" onClick={() => setSelected(l)}><Icon name="eye" size={15} /></button>
                      <button className="lv-act primary" aria-label="Verify" title="Verify lead" onClick={() => act(l, "Marked verified", `${l.name} moved to Verified.`, "success")}><Icon name="check-circle" size={15} /></button>
                      <button className="lv-act" aria-label="More actions" title="More actions" onClick={(e) => setMenu(menu?.lead.id === l.id ? null : { lead: l, x: e.clientX, y: e.clientY })}><Icon name="dots" size={15} /></button>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
      <div className="lv-count">{rows.length} of {V_LEADS.length} leads</div>

      <ActionsMenu menu={menu} onClose={() => setMenu(null)} onAct={act} onView={(l) => { setSelected(l); setMenu(null); }} />
      <VerifyDetail lead={selected} onClose={() => setSelected(null)} />
    </div>
  );
}

/* ---------------------------------------------------------- */
/* Row actions dropdown (portalled, fixed-positioned)          */
/* ---------------------------------------------------------- */

function ActionsMenu({ menu, onClose, onAct, onView }: {
  menu: MenuState; onClose: () => void;
  onAct: (l: VLead, title: string, desc: string, tone?: "success" | "info") => void;
  onView: (l: VLead) => void;
}) {
  const [mounted, setMounted] = useState(false);
  useEffect(() => { setMounted(true); }, []);
  useEffect(() => {
    if (!menu) return;
    const onKey = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [menu, onClose]);
  if (!menu || !mounted) return null;

  const l = menu.lead;
  const left = Math.max(8, menu.x - 196);
  const top = Math.min(menu.y + 8, window.innerHeight - 260);

  const items = [
    { icon: "eye", label: "View Details", run: () => onView(l) },
    { icon: "check-circle", label: "Verify Lead", run: () => onAct(l, "Verified", `${l.name} marked as verified.`, "success") },
    { icon: "alert", label: "Mark Unverified", run: () => onAct(l, "Marked unverified", `${l.name} moved to Unverified.`) },
    { icon: "user", label: "Change Assignee", run: () => onAct(l, "Change assignee", `Pick a new rep for ${l.name}.`) },
    { icon: "refresh", label: "Reassign (In Progress)", run: () => onAct(l, "Reassigned", `${l.name} set to In Progress.`) },
    { icon: "clock", label: "Move to Pending", run: () => onAct(l, "Moved to pending", `${l.name} is now Pending review.`) },
  ];

  return createPortal(
    <>
      <div className="lv-menu-scrim" onClick={onClose} />
      <div className="lv-menu" style={{ left, top }} role="menu">
        {items.map((it) => (
          <button key={it.label} className="lv-menu-item" role="menuitem" onClick={it.run}>
            <Icon name={it.icon} size={14} /> {it.label}
          </button>
        ))}
      </div>
    </>,
    document.body,
  );
}

/* ---------------------------------------------------------- */
/* Verification detail popup                                   */
/* ---------------------------------------------------------- */

function VerifyDetail({ lead, onClose }: { lead: VLead | null; onClose: () => void }) {
  if (!lead) return null;
  const meta = V_STATUS_META[lead.status];
  const activity = buildActivity(lead);

  return (
    <Modal open={!!lead} onClose={onClose} size="lg" title={lead.name} subtitle={`${lead.id} · ${lead.verification}`} icon="verify"
      footer={<>
        <Btn variant="ghost" icon="phone">Call</Btn>
        <Btn icon="check-circle">Verify Lead</Btn>
      </>}
    >
      <div className="lv-detail">
        <div className="lv-d-identity">
          <Avatar initials={lead.initials} size={50} />
          <div>
            <div className="lv-d-name">{lead.name}</div>
            <div className="lv-d-pills">
              <Pill tone={meta.tone}>{meta.label}</Pill>
              <span className={`lv-verif v-${lead.status}`}><Icon name={STAT_ICON[lead.status]} size={13} /> {lead.verification}</span>
            </div>
          </div>
        </div>

        <div className="lv-d-grid">
          <div className="lv-d-section">
            <div className="lv-d-head"><Icon name="user" size={15} /> Contact</div>
            <Row label="Phone" value={lead.phone} />
            <Row label="Email" value={deriveEmail(lead)} />
            <Row label="Address" value={lead.address} />
            <Row label="Source" value={lead.source} />
          </div>
          <div className="lv-d-section">
            <div className="lv-d-head"><Icon name="team" size={15} /> Assignment</div>
            <Row label="Assigned To" value={lead.assignee?.name ?? "Unassigned"} />
            <Row label="Created" value={deriveCreatedAt(lead)} />
            {lead.verifiedAt && <Row label="Verified At" value={lead.verifiedAt} />}
          </div>
        </div>

        {lead.notes && (
          <div className="lv-d-notes">
            <div className="lv-d-head"><Icon name="edit" size={15} /> Verification Notes</div>
            <p>{lead.notes}</p>
          </div>
        )}

        <div className="lv-d-activity">
          <div className="lv-d-head"><Icon name="clock" size={15} /> Activity</div>
          <ul className="lv-timeline">
            {activity.map((a, i) => (
              <li key={i} className="lv-tl-item">
                <span className="lv-tl-dot" />
                <div className="lv-tl-body">
                  <div className="lv-tl-text">{a.text}</div>
                  <div className="lv-tl-meta">{a.time} · {a.who}</div>
                </div>
              </li>
            ))}
          </ul>
        </div>
      </div>
    </Modal>
  );
}

function Row({ label, value }: { label: string; value: string }) {
  return (
    <div className="lv-d-row">
      <span className="lv-d-k">{label}</span>
      <span className="lv-d-v">{value}</span>
    </div>
  );
}
