import Link from "next/link";
import { requireOrg } from "@/lib/ctx";
import { STAGES, STAGE_LABEL, isStage } from "@/lib/stage-defs";

type Row = Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any

const fmt = (iso: string | null) =>
  iso ? new Date(iso).toLocaleString("id-ID", { day: "2-digit", month: "short", hour: "2-digit", minute: "2-digit", timeZone: "Asia/Jakarta" }) : "-";

export default async function Leads({ searchParams }: { searchParams: Promise<{ stage?: string; temp?: string; q?: string }> }) {
  const sp = await searchParams;
  const c = await requireOrg();

  let query = c.db
    .from("leads")
    .select("id, customer_name, phone, stage, temperature, score, last_message_at, assigned_to, created_at")
    .order("created_at", { ascending: false })
    .limit(200);
  if (sp.stage && isStage(sp.stage)) query = query.eq("stage", sp.stage);
  if (sp.temp && ["hot", "warm", "cold"].includes(sp.temp)) query = query.eq("temperature", sp.temp);
  const q = (sp.q ?? "").replace(/[,()%*]/g, "").trim();
  if (q) query = query.or(`customer_name.ilike.%${q}%,phone.ilike.%${q}%`);

  const { data } = await query;
  const leads: Row[] = data ?? [];

  const ids = [...new Set(leads.map((l) => l.assigned_to).filter(Boolean))];
  const { data: people } = ids.length ? await c.db.from("profiles").select("id, full_name").in("id", ids) : { data: [] as Row[] };
  const nameOf = new Map<string, string>((people ?? []).map((p: Row) => [p.id, p.full_name ?? "-"]));

  return (
    <>
      <h1>Lead</h1>
      <form className="card row fill" method="get">
        <input name="q" placeholder="Cari nama / nomor" defaultValue={sp.q ?? ""} />
        <select name="stage" defaultValue={sp.stage ?? ""}>
          <option value="">Semua tahap</option>
          {STAGES.map((s) => <option key={s} value={s}>{STAGE_LABEL[s]}</option>)}
        </select>
        <select name="temp" defaultValue={sp.temp ?? ""}>
          <option value="">Semua suhu</option>
          <option value="hot">Hot</option><option value="warm">Warm</option><option value="cold">Cold</option>
        </select>
        <button className="btn">Filter</button>
      </form>

      <div className="card scroll">
        <table>
          <thead><tr><th>Customer</th><th>Suhu</th><th>Tahap</th><th>Chat terakhir</th><th>CS</th></tr></thead>
          <tbody>
            {leads.map((l) => (
              <tr key={l.id}>
                <td>
                  <Link href={`/leads/${l.id}`}>{l.customer_name || l.phone || "(tanpa nama)"}</Link>
                  <div className="muted">{l.phone}</div>
                </td>
                <td>{l.temperature ? <span className={`badge ${l.temperature}`}>{l.temperature} {l.score}</span> : "-"}</td>
                <td>{STAGE_LABEL[l.stage as keyof typeof STAGE_LABEL]}</td>
                <td>{fmt(l.last_message_at)}</td>
                <td>{nameOf.get(l.assigned_to) ?? "-"}</td>
              </tr>
            ))}
            {!leads.length && <tr><td colSpan={5} className="muted">Belum ada lead.</td></tr>}
          </tbody>
        </table>
      </div>
    </>
  );
}
