import Link from "next/link";
import { requireSession } from "@/lib/auth";
import { LEAD_STATUSES, LEAD_LABEL, LEAD_TONE } from "@/lib/lead-status";
import { LEAD_PAGE_SIZE, leadFilterOptions, loadLeadList, parseLeadQuery, type LeadQuery, type LeadRow } from "@/lib/lead-list";
import { formatDate, formatNumber, STAGE_LABEL } from "@/lib/format";
import { ActionForm } from "@/components/action-form";
import { PageHeader, TableWrap, Badge } from "@/components/ui";
import { loadCustomerFormOptions } from "../form-options";
import { assignLeadsAction } from "../actions";
import { CustomerTabs } from "../customer-tabs";
import { SelectAll } from "./select-all";

export const dynamic = "force-dynamic";

const areaOf = (row: Pick<LeadRow, "ward" | "territoryName">) => [row.ward, row.territoryName].filter(Boolean).join(" - ") || "—";

export default async function LeadListPage({ searchParams }: { searchParams: Promise<Record<string, string | undefined>> }) {
  const session = await requireSession();
  const params = await searchParams;
  const query = parseLeadQuery((key) => params[key]);

  const [list, options, formOptions] = await Promise.all([
    loadLeadList(session, query),
    leadFilterOptions(session),
    loadCustomerFormOptions(session),
  ]);
  const { rows, total, page, totalPages, counts } = list;
  const canAssign = session.role !== "SALES";
  const isDirector = session.role === "DIRECTOR";

  const queryString = (patch: Partial<LeadQuery> = {}) => {
    const next = { ...query, page: 1, ...patch };
    const qs = new URLSearchParams();
    const set = (key: string, value: string | number, skip = false) => {
      if (!skip && value !== "" && value !== 0) qs.set(key, String(value));
    };
    set("q", next.q);
    set("tt", next.status);
    set("kv", next.territory);
    set("nv", next.owner);
    set("loai", next.channel);
    set("nguon", next.source);
    set("tu", next.from);
    set("den", next.to);
    set("xep", next.order, next.order === "moi");
    set("trang", next.page, next.page === 1);
    return qs.toString();
  };
  const href = (patch: Partial<LeadQuery> = {}) => {
    const text = queryString(patch);
    return text ? `/khach-hang/tiem-nang?${text}` : "/khach-hang/tiem-nang";
  };
  const exportHref = `/api/xuat-excel?loai=khach-tiem-nang${queryString() ? `&${queryString()}` : ""}`;
  const filtersActive = !!(query.q || query.status || query.territory || query.owner || query.channel || query.source || query.from || query.to);

  const statusBadge = (row: LeadRow) => (
    <div className="flex flex-col items-start gap-1">
      <Badge tone={LEAD_TONE[row.leadStatus] ?? "neutral"}>{LEAD_LABEL[row.leadStatus] ?? row.leadStatus}</Badge>
      {row.leadStatus === "CONVERTED" && <span className="text-[11px] text-ink-400">nay là {STAGE_LABEL[row.stage]}</span>}
      {row.lastReport && (
        <span className="max-w-64 text-[11px] leading-snug text-ink-500" title={row.lastReport.text}>
          {formatDate(row.lastReport.at)}: {row.lastReport.text.length > 110 ? `${row.lastReport.text.slice(0, 110)}…` : row.lastReport.text}
        </span>
      )}
    </div>
  );

  const phoneLink = (phone: string | null) =>
    phone ? (
      <a href={`tel:${phone.replace(/[^\d+]/g, "")}`} className="hover:text-brand-600 hover:underline">
        {phone}
      </a>
    ) : (
      <span className="text-ink-300">—</span>
    );

  const displayName = (row: LeadRow) => row.contactName ?? row.orgName;
  const hasOrgName = (row: LeadRow) => !!row.contactName && row.orgName !== row.contactName;

  return (
    <>
      <PageHeader
        title="Khách tiềm năng"
        subtitle="Dữ liệu ban đầu từ Marketing, chưa chuyển thành khách. Báo cáo từng lần liên hệ; chốt được thì chuyển thành khách."
        actions={
          <>
            <a href={exportHref} className="btn-ghost" download>
              Xuất Excel
            </a>
            <Link href="/khach-hang/moi" className="btn-primary">
              Thêm khách tiềm năng
            </Link>
          </>
        }
      />

      <CustomerTabs active="tiem-nang" />

      {/* Lọc nhanh theo trạng thái chuyển đổi, kèm số khách */}
      <div className="flex flex-wrap gap-1.5">
        {[{ key: "", label: "Tất cả" }, ...LEAD_STATUSES.map((s) => ({ key: s.key as string, label: s.label }))].map((item) => (
          <Link
            key={item.key || "all"}
            href={href({ status: item.key as LeadQuery["status"] })}
            className={`rounded-full border px-3 py-1 text-sm font-semibold ${
              query.status === item.key ? "border-brand-500 bg-brand-500 text-white" : "border-[var(--color-line)] bg-white text-ink-500 hover:bg-ink-50"
            }`}
          >
            {item.label} <span className="tnum font-normal opacity-80">{formatNumber(counts[item.key] ?? 0)}</span>
          </Link>
        ))}
      </div>

      <form className="mt-4 flex flex-wrap items-end gap-3" action="/khach-hang/tiem-nang">
        {query.status && <input type="hidden" name="tt" value={query.status} />}
        <div className="min-w-48 flex-1">
          <label htmlFor="q" className="label-caps mb-1.5 block">
            Tìm kiếm
          </label>
          <input id="q" name="q" defaultValue={query.q} className="input" placeholder="Tên, SĐT, phường, nhu cầu…" />
        </div>
        {options.territories.length > 0 && (
          <div>
            <label htmlFor="kv" className="label-caps mb-1.5 block">
              Tỉnh / thành
            </label>
            <select id="kv" name="kv" defaultValue={query.territory} className="input">
              <option value="">Tất cả</option>
              {options.territories.map((t) => (
                <option key={t.id} value={t.id}>
                  {t.name}
                </option>
              ))}
            </select>
          </div>
        )}
        {options.channels.length > 0 && (
          <div>
            <label htmlFor="loai" className="label-caps mb-1.5 block">
              Loại
            </label>
            <select id="loai" name="loai" defaultValue={query.channel} className="input">
              <option value="">Tất cả</option>
              {options.channels.map((c) => (
                <option key={c.id} value={c.id}>
                  {c.name}
                </option>
              ))}
            </select>
          </div>
        )}
        {options.sources.length > 0 && (
          <div>
            <label htmlFor="nguon" className="label-caps mb-1.5 block">
              Nguồn khách
            </label>
            <select id="nguon" name="nguon" defaultValue={query.source} className="input">
              <option value="">Tất cả</option>
              {options.sources.map((source) => (
                <option key={source} value={source}>
                  {source}
                </option>
              ))}
            </select>
          </div>
        )}
        {(options.owners.length > 0 || isDirector) && (
          <div>
            <label htmlFor="nv" className="label-caps mb-1.5 block">
              Người phụ trách
            </label>
            <select id="nv" name="nv" defaultValue={query.owner} className="input">
              <option value="">Tất cả</option>
              {isDirector && <option value="none">Chưa phân công</option>}
              {options.owners.map((o) => (
                <option key={o.id} value={o.id}>
                  {o.name}
                </option>
              ))}
            </select>
          </div>
        )}
        <div>
          <label htmlFor="tu" className="label-caps mb-1.5 block">
            Thêm từ ngày
          </label>
          <input id="tu" name="tu" type="date" defaultValue={query.from} className="input" />
        </div>
        <div>
          <label htmlFor="den" className="label-caps mb-1.5 block">
            đến ngày
          </label>
          <input id="den" name="den" type="date" defaultValue={query.to} className="input" />
        </div>
        <div>
          <label htmlFor="xep" className="label-caps mb-1.5 block">
            Sắp xếp
          </label>
          <select id="xep" name="xep" defaultValue={query.order} className="input">
            <option value="moi">Mới thêm trước</option>
            <option value="cu">Cũ nhất trước</option>
          </select>
        </div>
        <button type="submit" className="btn-ghost">
          Lọc
        </button>
        {(filtersActive || query.order !== "moi") && (
          <Link href="/khach-hang/tiem-nang" className="pb-2 text-sm text-ink-500 hover:underline">
            Bỏ lọc
          </Link>
        )}
      </form>

      <p className="mt-2 text-xs text-ink-400">{formatNumber(total)} khách tiềm năng phù hợp</p>

      {/* Điện thoại / màn hình nhỏ: mỗi khách một thẻ */}
      <div className="mt-4 flex flex-col gap-2 xl:hidden">
        {rows.length === 0 && <div className="card px-4 py-8 text-center text-sm text-ink-400">Không có khách tiềm năng phù hợp bộ lọc.</div>}
        {rows.map((row) => (
          <div key={row.id} className="card p-3.5">
            <Link href={`/khach-hang/${row.id}`} className="block active:opacity-70">
              <div className="flex items-start justify-between gap-3">
                <div className="min-w-0">
                  <div className="font-semibold text-ink-700">{displayName(row)}</div>
                  {hasOrgName(row) && <div className="text-[11px] text-ink-400">{row.orgName}</div>}
                </div>
                <Badge tone={LEAD_TONE[row.leadStatus] ?? "neutral"}>{LEAD_LABEL[row.leadStatus] ?? row.leadStatus}</Badge>
              </div>
            </Link>
            <dl className="mt-2 grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5 text-xs">
              <dt className="text-ink-400">Ngày thêm</dt>
              <dd className="text-ink-600">{formatDate(row.createdAt)}</dd>
              <dt className="text-ink-400">Điện thoại</dt>
              <dd className="text-ink-600">{phoneLink(row.phone)}</dd>
              <dt className="text-ink-400">Khu vực</dt>
              <dd className="text-ink-600">{areaOf(row)}</dd>
              <dt className="text-ink-400">Loại</dt>
              <dd className="text-ink-600">{row.channelName ?? "—"}</dd>
              <dt className="text-ink-400">Nhu cầu</dt>
              <dd className="text-ink-600">{row.leadNeed ?? "—"}</dd>
              <dt className="text-ink-400">Nguồn</dt>
              <dd className="text-ink-600">{row.leadSource ?? "—"}</dd>
              <dt className="text-ink-400">Phụ trách</dt>
              <dd className="text-ink-600">{row.ownerName ?? "Chưa phân công"}</dd>
            </dl>
            {row.lastReport && (
              <p className="mt-2 border-t border-line pt-2 text-[11px] text-ink-500">
                Báo cáo {formatDate(row.lastReport.at)}: {row.lastReport.text}
              </p>
            )}
          </div>
        ))}
      </div>

      {/* Máy tính: bảng đúng các cột khách yêu cầu; quản lý chọn nhiều khách để giao cho NVKD */}
      <div className="mt-4 hidden xl:block">
        <ActionForm action={assignLeadsAction} success="Đã giao khách tiềm năng.">
          {canAssign && rows.length > 0 && (
            <div className="card mb-3 flex flex-wrap items-center gap-2 p-3">
              <span className="text-sm font-semibold text-ink-600">Giao các khách đã tick cho:</span>
              <select name="ownerId" className="input w-auto" defaultValue="" aria-label="NVKD nhận khách">
                <option value="" disabled>
                  — Chọn NVKD —
                </option>
                {formOptions.staff.map((person) => (
                  <option key={person.id} value={person.id}>
                    {person.name}
                  </option>
                ))}
              </select>
              <button type="submit" className="btn-ghost">
                Giao khách
              </button>
              {isDirector && <span className="text-[11px] text-ink-400">Khách chưa phân công chỉ Ban giám đốc nhìn thấy — giao xong NVKD mới thấy.</span>}
            </div>
          )}
          <TableWrap>
            <thead>
              <tr>
                {canAssign && (
                  <th className="w-8">
                    <SelectAll />
                  </th>
                )}
                <th>Ngày thêm mới</th>
                <th>Họ tên người liên hệ</th>
                <th>Điện thoại</th>
                <th>Khu vực (Phường - Tỉnh)</th>
                <th>Loại</th>
                <th>Nhu cầu tư vấn</th>
                <th>Nguồn khách</th>
                <th>Trạng thái chuyển đổi</th>
                <th>Phụ trách</th>
              </tr>
            </thead>
            <tbody>
              {rows.length === 0 && (
                <tr>
                  <td colSpan={canAssign ? 10 : 9} className="py-10 text-center text-ink-400">
                    Không có khách tiềm năng phù hợp bộ lọc.
                  </td>
                </tr>
              )}
              {rows.map((row) => (
                <tr key={row.id} className="align-top">
                  {canAssign && (
                    <td>
                      {row.stage === "LEAD" && <input type="checkbox" name="ids" value={row.id} aria-label={`Chọn ${displayName(row)}`} className="h-4 w-4 accent-brand-500" />}
                    </td>
                  )}
                  <td className="tnum whitespace-nowrap text-ink-600">{formatDate(row.createdAt)}</td>
                  <td>
                    <Link href={`/khach-hang/${row.id}`} className="font-medium text-ink-700 hover:text-brand-600">
                      {displayName(row)}
                    </Link>
                    <div className="text-[11px] text-ink-400">
                      {row.code}
                      {row.contactPosition ? ` · ${row.contactPosition}` : ""}
                      {hasOrgName(row) ? ` · ${row.orgName}` : ""}
                    </div>
                  </td>
                  <td className="whitespace-nowrap text-ink-600">{phoneLink(row.phone)}</td>
                  <td className="min-w-36 text-ink-600">{areaOf(row)}</td>
                  <td className="text-ink-600">{row.channelName ?? "—"}</td>
                  <td className="max-w-56 text-ink-600">{row.leadNeed ?? "—"}</td>
                  <td className="text-ink-600">{row.leadSource ?? "—"}</td>
                  <td>{statusBadge(row)}</td>
                  <td className="text-ink-600">{row.ownerName ?? <span className="text-gold-500">Chưa phân công</span>}</td>
                </tr>
              ))}
            </tbody>
          </TableWrap>
        </ActionForm>
      </div>

      {totalPages > 1 && (
        <nav className="mt-4 flex items-center justify-center gap-3 text-sm" aria-label="Phân trang">
          {page > 1 ? (
            <Link href={href({ page: page - 1 })} className="btn-ghost">
              ← Trước
            </Link>
          ) : (
            <span className="btn-ghost pointer-events-none opacity-40">← Trước</span>
          )}
          <span className="text-ink-500">
            Trang {page}/{totalPages} · {(page - 1) * LEAD_PAGE_SIZE + 1}–{Math.min(page * LEAD_PAGE_SIZE, total)} / {formatNumber(total)}
          </span>
          {page < totalPages ? (
            <Link href={href({ page: page + 1 })} className="btn-ghost">
              Sau →
            </Link>
          ) : (
            <span className="btn-ghost pointer-events-none opacity-40">Sau →</span>
          )}
        </nav>
      )}

      <p className="mt-3 text-xs text-ink-400">
        Trạng thái: <b>Chưa liên hệ</b> → <b>Đã liên hệ</b> hoặc <b>Đã huỷ</b> (bắt buộc báo cáo) → <b>Đã chốt</b> = chuyển thành khách “Đang” / Đại lý (bắt buộc báo cáo). Mở khách để cập nhật trạng thái.
        Khách đã chốt vẫn nằm trong danh sách này để lọc và đối chiếu kết quả của Marketing.
      </p>
    </>
  );
}
