"use client";

// ============================================================
// Projects — Construction jobs + Pipeline leads.
// Data comes from useProjectsData(): the local mock when the
// Shell isn't configured, or the live be-crm data door
// (crm.project.*) when it is. be-crm's Project model is generic
// (name/status/value/owner/address/dates) — mock mode additionally
// carries stage, job type, progress and health, which the live
// table simply doesn't render (nothing backs them).
// ============================================================

import { useMemo, useState } from "react";
import { Btn, Icon, Modal, PageHead, Pill } from "./ui";
import {
  QUICK_FILTERS, STATUS_LABEL, STATUS_TONE, useProjectsData,
  type UiCollectionRecord, type UiProject, type UiProjectStatus,
} from "@/lib/projects-api";

const money = (n: number) => `$${Math.round(n).toLocaleString()}`;
// The collections ledger shows cents (matches invoice-style amounts); the rest of the page rounds to whole dollars.
const moneyExact = (n: number) => `$${n.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;

const COLLECTION_STATUS_LABEL: Record<UiCollectionRecord["status"], string> = { paid: "Paid", pending: "Pending", overdue: "Overdue" };
const COLLECTION_STATUS_TONE: Record<UiCollectionRecord["status"], string> = { paid: "green", pending: "orange", overdue: "red" };

export function Projects() {
  const data = useProjectsData();
  const { projects, live } = data;

  const [tab, setTab] = useState<"construction" | "pipeline">("construction");
  const [query, setQuery] = useState("");
  const [statusFilter, setStatusFilter] = useState<"all" | UiProjectStatus>("all");
  const [viewProject, setViewProject] = useState<UiProject | null>(null);

  const construction = useMemo(() => projects.filter((p) => !p.isLead), [projects]);
  const pipeline = useMemo(() => projects.filter((p) => p.isLead), [projects]);
  const budgetTotal = useMemo(() => construction.reduce((s, p) => s + (p.value ?? 0), 0), [construction]);

  const list = tab === "construction" ? construction : pipeline;
  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    return list.filter((p) => {
      const matchesStatus = tab === "pipeline" || statusFilter === "all" || p.status === statusFilter;
      const matchesQ = !q
        || p.name.toLowerCase().includes(q)
        || (p.address ?? "").toLowerCase().includes(q)
        || (p.jobType ?? "").toLowerCase().includes(q)
        || p.agent.toLowerCase().includes(q);
      return matchesStatus && matchesQ;
    });
  }, [list, statusFilter, query, tab]);

  // Mock construction (richest): Lead | Status | Stage | Job Type | Agent | Progress | Health | ⋯
  // Mock pipeline: Lead | Job Type | Stage | Agent | Created | ⋯
  // Live (either tab, leaner — only fields be-crm actually stores): Lead | Status | Owner | Value | Due date | ⋯
  const template = live
    ? "minmax(220px,2.3fr) 110px 160px 120px 130px 48px"
    : tab === "construction"
      ? "minmax(220px,2.2fr) 104px 130px 150px 130px 130px 76px 48px"
      : "minmax(220px,2.2fr) 150px 140px 130px 120px 48px";

  return (
    <div className="view proj">
      <PageHead
        title="Projects"
        subtitle={`${construction.length} construction · ${pipeline.length} pipeline leads · ${money(budgetTotal)} budget`}
      />

      {data.error && <div className="card proj-empty" style={{ borderColor: "var(--red, #ef4444)" }}><p>Couldn&apos;t load projects: {data.error}</p></div>}

      <div className="tm-toolbar proj-toolbar">
        <div className="tm-tabs" role="tablist">
          <button role="tab" aria-selected={tab === "construction"} className={`tm-tab ${tab === "construction" ? "active" : ""}`} onClick={() => setTab("construction")}>
            <Icon name="owners" size={16} /> <span>Construction</span>
            <span className="tm-tab-badge">{construction.length}</span>
          </button>
          <button role="tab" aria-selected={tab === "pipeline"} className={`tm-tab ${tab === "pipeline" ? "active" : ""}`} onClick={() => setTab("pipeline")}>
            <Icon name="pipeline" size={16} /> <span>Pipeline Leads</span>
            <span className="tm-tab-badge">{pipeline.length}</span>
          </button>
        </div>

        <div className="tm-search">
          <Icon name="search" size={16} />
          <input className="ds-input flush" placeholder="Search leads by name, address, job type, agent…" value={query} onChange={(e) => setQuery(e.target.value)} />
          {query && <button className="tm-search-x" aria-label="Clear" onClick={() => setQuery("")}><Icon name="x" size={14} /></button>}
        </div>

        {tab === "construction" && (
          <div className="tm-chips">
            <button className={`tm-chip ${statusFilter === "all" ? "on" : ""}`} onClick={() => setStatusFilter("all")}>
              All <i>{construction.length}</i>
            </button>
            {QUICK_FILTERS.map((s) => (
              <button key={s} className={`tm-chip ${statusFilter === s ? "on" : ""}`} style={{ ["--rc" as string]: `var(--${STATUS_TONE[s] === "muted" ? "faint" : STATUS_TONE[s]})` }} onClick={() => setStatusFilter(s)}>
                {STATUS_LABEL[s]} <i>{construction.filter((p) => p.status === s).length}</i>
              </button>
            ))}
          </div>
        )}
      </div>

      {data.live && data.loading && projects.length === 0 ? (
        <div className="card proj-empty"><span className="tm-empty-ic"><Icon name="owners" size={24} /></span><p>Loading projects…</p></div>
      ) : filtered.length === 0 ? (
        <div className="card proj-empty">
          <span className="tm-empty-ic"><Icon name="search" size={24} /></span>
          <p>No {tab === "construction" ? "projects" : "leads"} match your search.</p>
          <Btn variant="soft" size="sm" onClick={() => { setQuery(""); setStatusFilter("all"); }}>Clear filters</Btn>
        </div>
      ) : (
        <div className="card card-pad-0 proj-table">
          <div className="proj-row proj-head" style={{ gridTemplateColumns: template }}>
            <span>Lead</span>
            {live ? (
              <><span>Status</span><span>Owner</span><span className="proj-c-num">Value</span><span>Due date</span></>
            ) : tab === "construction" ? (
              <><span>Status</span><span>Stage</span><span>Job type</span><span>Agent</span><span>Progress</span><span className="proj-c-num">Health</span></>
            ) : (
              <><span>Job type</span><span>Stage</span><span>Agent</span><span>Created</span></>
            )}
            <span className="proj-c-act" />
          </div>

          {filtered.map((p) => (
            <div className="proj-row" key={p.id} style={{ gridTemplateColumns: template }}>
              <div className="proj-lead">
                <div className="proj-lead-name">{p.name}</div>
                {p.address && <div className="proj-lead-sub">{p.address}</div>}
              </div>

              {live ? (
                <>
                  <Pill tone={STATUS_TONE[p.status]}>{STATUS_LABEL[p.status].toUpperCase()}</Pill>
                  <span className="proj-text">{p.agent}</span>
                  <span className="proj-c-num">{p.value != null ? money(p.value) : <span className="tm-dash">—</span>}</span>
                  <span className="proj-text">{p.dueDate ? new Date(p.dueDate).toLocaleDateString(undefined, { day: "numeric", month: "short", year: "numeric" }) : <span className="tm-dash">—</span>}</span>
                </>
              ) : tab === "construction" ? (
                <>
                  <Pill tone={STATUS_TONE[p.status]}>{STATUS_LABEL[p.status].toUpperCase()}</Pill>
                  <Pill tone="blue">{p.stage}</Pill>
                  <span className="proj-text">{p.jobType}</span>
                  <span className="proj-text">{p.agent}</span>
                  <div className="proj-progress" title={`${p.progress}%`}>
                    <span className="proj-progress-track"><span className="proj-progress-fill" style={{ width: `${p.progress ?? 0}%` }} /></span>
                    <b>{p.progress}%</b>
                  </div>
                  <span className="proj-c-num proj-health">{p.health}</span>
                </>
              ) : (
                <>
                  <span className="proj-text">{p.jobType}</span>
                  <Pill tone="blue">{p.stage}</Pill>
                  <span className="proj-text">{p.agent}</span>
                  <span className="proj-text">{p.createdAgo}</span>
                </>
              )}

              <div className="proj-c-act">
                <button className="ds-iconbtn" aria-label={`View collections for ${p.name}`} onClick={() => setViewProject(p)}><Icon name="eye" size={17} /></button>
              </div>
            </div>
          ))}
        </div>
      )}

      <div className="proj-foot">
        <span>Showing {filtered.length} of {list.length} {tab === "construction" ? "projects" : "leads"}</span>
        {tab === "construction" && <b>{money(budgetTotal)} total</b>}
      </div>

      <CollectedDetailsModal project={viewProject} onClose={() => setViewProject(null)} />
    </div>
  );
}

/* ---------------------------------------------------------- */
/* Collected details modal — payment ledger for one project   */
/* ---------------------------------------------------------- */

function CollectedDetailsModal({ project, onClose }: { project: UiProject | null; onClose: () => void }) {
  const [query, setQuery] = useState("");
  const records = project?.collections ?? [];
  const total = useMemo(() => records.reduce((s, r) => s + r.amount, 0), [records]);
  if (!project) return null;

  const q = query.trim().toLowerCase();
  const filtered = records.filter((r) =>
    !q || r.name.toLowerCase().includes(q) || r.referenceId.toLowerCase().includes(q) || r.type.toLowerCase().includes(q));
  const netTotal = filtered.reduce((s, r) => s + r.amount, 0);
  const projectName = project.name;

  function downloadCsv() {
    const header = ["Name/Project", "Reference ID", "Date", "Type", "Status", "Amount"];
    const rows = filtered.map((r) => [r.name, r.referenceId, r.date, r.type, COLLECTION_STATUS_LABEL[r.status], r.amount.toFixed(2)]);
    const csv = [header, ...rows].map((row) => row.map((c) => `"${String(c).replace(/"/g, '""')}"`).join(",")).join("\n");
    const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `${projectName.replace(/\s+/g, "-").toLowerCase()}-collections.csv`;
    a.click();
    URL.revokeObjectURL(url);
  }

  return (
    <Modal
      open={!!project}
      onClose={onClose}
      title="Total Collected Details"
      subtitle={<>Total: <b>{moneyExact(total)}</b></>}
      size="xl"
      headerExtra={records.length > 0 && (
        <button className="ds-iconbtn" aria-label="Download CSV" onClick={downloadCsv}><Icon name="download" size={18} /></button>
      )}
    >
      {project.collections === null ? (
        <div className="tm-empty"><span className="tm-empty-ic"><Icon name="card" size={24} /></span><p>Collections aren&apos;t available yet for live projects — this needs a billing module in be-crm.</p></div>
      ) : records.length === 0 ? (
        <div className="tm-empty"><span className="tm-empty-ic"><Icon name="card" size={24} /></span><p>No payments collected yet for {project.name}.</p></div>
      ) : (
        <>
          <div className="tm-search proj-cd-search">
            <Icon name="search" size={16} />
            <input className="ds-input flush" placeholder="Search leads by name, address, job type, agent…" value={query} onChange={(e) => setQuery(e.target.value)} />
            {query && <button className="tm-search-x" aria-label="Clear" onClick={() => setQuery("")}><Icon name="x" size={14} /></button>}
          </div>

          <div className="card card-pad-0 proj-table proj-cd-table">
            <div className="proj-row proj-head" style={{ gridTemplateColumns: "minmax(180px,2fr) 140px 100px 170px 100px 120px" }}>
              <span>Name / Project</span><span>Reference ID</span><span>Date</span><span>Type</span><span>Status</span><span className="proj-c-num">Amount</span>
            </div>
            {filtered.map((r) => (
              <div className="proj-row" key={r.id} style={{ gridTemplateColumns: "minmax(180px,2fr) 140px 100px 170px 100px 120px" }}>
                <div className="proj-lead">
                  <div className="proj-lead-name">{r.name}</div>
                  <div className="proj-lead-sub">{r.address}</div>
                </div>
                <span className="proj-text">{r.referenceId}</span>
                <span className="proj-text">{r.date}</span>
                <span className="proj-text">{r.type}</span>
                <Pill tone={COLLECTION_STATUS_TONE[r.status]}>{COLLECTION_STATUS_LABEL[r.status].toUpperCase()}</Pill>
                <span className="proj-c-num">{moneyExact(r.amount)}</span>
              </div>
            ))}
          </div>

          <div className="proj-foot">
            <span>Showing {filtered.length} record{filtered.length === 1 ? "" : "s"}</span>
            <b>Net Total: {moneyExact(netTotal)}</b>
          </div>
        </>
      )}
    </Modal>
  );
}
