import { ActionForm } from "@/components/action-form";
import Link from "next/link";
import { requireSession } from "@/lib/auth";
import {
  coreMetrics,
  revenueByTerritory,
  revenueBySalesUser,
  revenueByProduct,
  promoGoodsByStaff,
  dealerActivity,
  targetFor,
  programProgress,
  newCustomerDetails,
} from "@/lib/reports";
import {
  periodRange,
  monthKey,
  today,
  weekStart,
  weekDays,
  quarterOfMonth,
  periodElapsed,
  isRealDate,
} from "@/lib/period";
import {
  formatVnd,
  formatVndShort,
  formatNumber,
  formatPercent,
  formatDate,
  formatPeriod,
  STAGE_LABEL,
} from "@/lib/format";
import { PageHeader, StatCard, TableWrap, SectionTitle, Badge, ProgressBar, TierBadge } from "@/components/ui";
import { promoReport, staffingReport } from "@/lib/sales-analysis";
import { customerOverview } from "@/lib/customer-report";
import { transferList, transferOverview } from "@/lib/transfer-report";
import { PromoBreakdown } from "../phan-tich/views";
import { saveInactiveReasonAction } from "./actions";
import { FocusSelect } from "@/components/focus-select";
import { loadFocusOptions, withFocus, parseFocus } from "@/lib/focus";

export const dynamic = "force-dynamic";

type Tab = "ngay" | "tuan" | "thang" | "quy" | "nam";

const TABS: { key: Tab; label: string }[] = [
  { key: "ngay", label: "Ngày" },
  { key: "tuan", label: "Tuần" },
  { key: "thang", label: "Tháng" },
  { key: "quy", label: "Quý" },
  { key: "nam", label: "Năm" },
];

/**
 * Ba tầng báo cáo ngày/tuần/tháng dùng chung một bộ chỉ số, chỉ khác khoảng
 * ngày — nên chỉ có một trang, đổi kỳ bằng tab, thay vì ba màn hình gần giống nhau.
 */
export default async function ReportsPage({
  searchParams,
}: {
  searchParams: Promise<{ ky?: string; ngay?: string; pv?: string }>;
}) {
  const baseSession = await requireSession();
  const params = await searchParams;
  const session = withFocus(baseSession, params.pv);
  const focusOptions = await loadFocusOptions(baseSession);
  const pvValue = parseFocus(params.pv) && baseSession.role !== "SALES" ? params.pv : "";
  const pvQuery = pvValue ? `&pv=${pvValue}` : "";
  const tab: Tab = TABS.some((t) => t.key === params.ky) ? (params.ky as Tab) : "thang";
  // Mốc thời gian gõ trên đường dẫn phải là ngày có thật — sai thì dùng hôm nay (đưa thẳng vào truy vấn ngày sẽ báo lỗi 500).
  const anchor = isRealDate(params.ngay) ? params.ngay : today();

  const monthPeriod = monthKey(anchor);
  const quarterPeriod = quarterOfMonth(monthPeriod);
  const yearPeriod = anchor.slice(0, 4);

  const range =
    tab === "ngay"
      ? { start: anchor, end: anchor }
      : tab === "tuan"
        ? (() => {
            const days = weekDays(weekStart(anchor));
            return { start: days[0], end: days[6] };
          })()
        : tab === "quy"
          ? periodRange(quarterPeriod)
          : tab === "nam"
            ? periodRange(yearPeriod)
            : periodRange(monthPeriod);

  /* Kỳ dùng để đo tiến độ kế hoạch. Báo cáo ngày và tuần vẫn quy về tháng, vì chỉ
     tiêu được giao theo tháng và người xem muốn biết "tháng này đã đi tới đâu". */
  const progressPeriod =
    tab === "nam" ? yearPeriod : tab === "quy" ? quarterPeriod : monthPeriod;

  const [metrics, byTerritory, bySales, byProduct, byStaffPromo, dealers, programs, eventList, newCustomers, promo, staffing, customerStats, eventOverview] =
    await Promise.all([
      coreMetrics(session, range),
      revenueByTerritory(session, range),
      revenueBySalesUser(session, range),
      revenueByProduct(session, range, 15),
      promoGoodsByStaff(session, range),
      dealerActivity(session, range, monthPeriod),
      programProgress(session, range),
      transferList(session, range, { pageSize: 50 }),
      newCustomerDetails(session, range),
      promoReport(session, range),
      staffingReport(session, progressPeriod, range),
      customerOverview(session, range, ""),
      transferOverview(session, range),
    ]);
  const events = eventList.rows;

  /* Kỳ đang xem có thể kéo tới cuối tháng trong tương lai, nên chặn ở ngày hôm nay:
     nếu không, tiến độ thời gian luôn hiện 100% và mọi kỳ đều trông như đang chậm. */
  const cutoff = range.end > today() ? today() : range.end;

  /** Luỹ tiến từ đầu kỳ tới thời điểm báo cáo, so với chỉ tiêu của kỳ đó. */
  async function progressOf(periodKey: string) {
    const bounds = periodRange(periodKey);
    const end = cutoff < bounds.start ? bounds.start : cutoff > bounds.end ? bounds.end : cutoff;
    const [achieved, target] = await Promise.all([
      coreMetrics(session, { start: bounds.start, end }),
      targetFor(session, periodKey),
    ]);
    const { elapsed, total } = periodElapsed(periodKey, cutoff);
    return {
      periodKey,
      revenue: achieved.revenue,
      target,
      elapsed,
      total,
      timePct: total > 0 ? (elapsed / total) * 100 : 0,
      achievementPct:
        target && target.revenueTarget > 0 ? (achieved.revenue / target.revenueTarget) * 100 : null,
    };
  }

  const primary = await progressOf(progressPeriod);

  /* Yêu cầu mục 4 đòi báo cáo tháng phải có cả "% thực hiện so với kế hoạch tháng"
     lẫn "% thực hiện theo tiến độ Quý" — nên tháng thì hiện thêm khối tiến độ quý. */
  const quarterProgress =
    tab === "thang" || tab === "ngay" || tab === "tuan" ? await progressOf(quarterPeriod) : null;

  const totalRevenue = byTerritory.reduce((sum, r) => sum + Number(r.revenue), 0);

  return (
    <>
      <PageHeader
        title="Báo cáo bán hàng"
        subtitle={`Từ ${formatDate(range.start)} đến ${formatDate(range.end)}`}
        actions={
          <>
            <Link href={`/bao-cao/chuyen-giao?ky=${tab}&ngay=${anchor}${pvQuery}`} className="btn-ghost">
              Chuyển giao
            </Link>
            <Link href={`/bao-cao/in?tu=${range.start}&den=${range.end}${pvQuery}`} className="btn-ghost">
              Bản in / PDF
            </Link>
            <a
              href={`/api/xuat-excel?loai=bao-cao&tu=${range.start}&den=${range.end}${pvQuery}`}
              className="btn-ghost"
              download
            >
              Xuất Excel
            </a>
          </>
        }
      />

      <form className="mb-5 flex flex-wrap items-end gap-3" action="/bao-cao">
        <div className="flex gap-1 rounded-lg border border-[var(--color-line)] bg-white p-1">
          {TABS.map((item) => (
            <Link
              key={item.key}
              href={`/bao-cao?ky=${item.key}&ngay=${anchor}${pvQuery}`}
              className={`rounded-md px-3 py-1.5 text-sm font-semibold ${
                tab === item.key ? "bg-brand-500 text-white" : "text-ink-500 hover:bg-ink-50"
              }`}
            >
              {item.label}
            </Link>
          ))}
        </div>
        <input type="hidden" name="ky" value={tab} />
        <div>
          <label htmlFor="ngay" className="label-caps mb-1.5 block">
            Mốc thời gian
          </label>
          <input id="ngay" name="ngay" type="date" defaultValue={anchor} className="input" />
        </div>
        <FocusSelect options={focusOptions} value={pvValue} />
        <button type="submit" className="btn-ghost">
          Xem
        </button>
      </form>

      <div className="grid grid-cols-2 gap-3 lg:grid-cols-5">
        <StatCard label="Số đơn hàng" value={formatNumber(metrics.orderCount)} />
        <StatCard label="Doanh thu" value={formatVndShort(metrics.revenue)} hint={formatVnd(metrics.revenue)} />
        <StatCard label="Số SKUs" value={formatNumber(metrics.skuCount)} />
        <StatCard label="Số ĐL lấy hàng" value={formatNumber(metrics.dealerCount)} />
        <StatCard label="KH mở mới" value={formatNumber(customerStats.newCount)} hint={customerStats.ratioPct != null ? `${formatPercent(customerStats.ratioPct, 1)} / tổng ${formatNumber(customerStats.total)} khách` : undefined} />
      </div>

      {/* Luỹ tiến tới thời điểm báo cáo — kèm tiến độ Quý theo yêu cầu mục 4 */}
      <div className={`mt-3 grid gap-3 ${quarterProgress ? "lg:grid-cols-2" : ""}`}>
        {[primary, quarterProgress].filter(Boolean).map((block) => (
          <div key={block!.periodKey} className="card p-4">
            <div className="mb-2 flex flex-wrap items-baseline justify-between gap-2">
              <span className="text-sm font-semibold text-ink-700">
                Luỹ tiến {formatPeriod(block!.periodKey)} tới {formatDate(cutoff)}
              </span>
              <span className="tnum text-sm text-ink-400">
                {formatVndShort(block!.revenue)}
                {block!.target
                  ? ` / ${formatVndShort(block!.target.revenueTarget)}`
                  : " · chưa giao chỉ tiêu"}
              </span>
            </div>
            {block!.achievementPct != null && (
              <ProgressBar percent={block!.achievementPct} benchmark={block!.timePct} />
            )}
            <div className="mt-2 flex flex-wrap justify-between gap-2 text-xs text-ink-400">
              <span>
                {block!.achievementPct != null
                  ? `Đã đạt ${formatPercent(block!.achievementPct)} kế hoạch`
                  : "Giao chỉ tiêu trong mục Danh mục để theo dõi tiến độ"}
              </span>
              <span className="tnum">
                Đã qua {block!.elapsed}/{block!.total} ngày ({formatPercent(block!.timePct)})
              </span>
            </div>
          </div>
        ))}
      </div>

      <div className="mt-6 grid gap-4 lg:grid-cols-2">
        <div>
          <SectionTitle hint="tỷ trọng thị trường">Doanh thu theo khu vực</SectionTitle>
          <TableWrap>
            <thead>
              <tr>
                <th>Khu vực</th>
                <th className="text-right">Số đơn</th>
                <th className="text-right">Số KH</th>
                <th className="text-right">Doanh thu</th>
                <th className="text-right">Tỷ trọng</th>
              </tr>
            </thead>
            <tbody>
              {byTerritory.length === 0 && (
                <tr>
                  <td colSpan={5} className="py-8 text-center text-ink-400">
                    Không có dữ liệu trong kỳ.
                  </td>
                </tr>
              )}
              {byTerritory.map((row) => (
                <tr key={row.territoryId ?? "none"}>
                  <td className="font-medium text-ink-700">{row.territoryName}</td>
                  <td className="tnum text-right text-ink-500">{row.orderCount}</td>
                  <td className="tnum text-right text-ink-500">{row.customerCount}</td>
                  <td className="tnum text-right font-medium">{formatVndShort(Number(row.revenue))}</td>
                  <td className="tnum text-right text-ink-400">
                    {totalRevenue > 0 ? formatPercent((Number(row.revenue) / totalRevenue) * 100, 1) : "—"}
                  </td>
                </tr>
              ))}
            </tbody>
          </TableWrap>
        </div>

        <div>
          <SectionTitle hint="định biên doanh thu">Doanh thu theo NVKD</SectionTitle>
          <TableWrap>
            <thead>
              <tr>
                <th>Nhân viên</th>
                <th className="text-right">Số đơn</th>
                <th className="text-right">Số KH</th>
                <th className="text-right">Doanh thu</th>
              </tr>
            </thead>
            <tbody>
              {bySales.length === 0 && (
                <tr>
                  <td colSpan={4} className="py-8 text-center text-ink-400">
                    Không có dữ liệu trong kỳ.
                  </td>
                </tr>
              )}
              {bySales.map((row) => (
                <tr key={row.userId ?? "none"}>
                  <td className="font-medium text-ink-700">{row.fullName}</td>
                  <td className="tnum text-right text-ink-500">{row.orderCount}</td>
                  <td className="tnum text-right text-ink-500">{row.customerCount}</td>
                  <td className="tnum text-right font-medium">{formatVndShort(Number(row.revenue))}</td>
                </tr>
              ))}
            </tbody>
          </TableWrap>
          {baseSession.role !== "SALES" && (
          <p className="mt-2 text-xs text-ink-400">
            Định biên {staffing.overall.headcount} NVKD
            {staffing.overall.perHead != null ? ` · bình quân ${formatVndShort(staffing.overall.perHead)}/NVKD trong kỳ` : ""}. Chi tiết theo team, khu vực ở{" "}
            <Link href={`/phan-tich?muc=dinh-bien&ky=${progressPeriod}${pvQuery}`} className="text-brand-600 hover:underline">
              Phân tích → Định biên
            </Link>
            ; xếp hạng nhân viên theo doanh thu, doanh số, công nợ, khách mở mới ở{" "}
            <Link href={`/phan-tich?muc=xep-hang&ky=${progressPeriod}${pvQuery}`} className="text-brand-600 hover:underline">
              Phân tích → Xếp hạng NV
            </Link>
            .
          </p>
          )}
        </div>
      </div>

      {/* Tiến độ chương trình bán hàng */}
      {programs.length > 0 && (
        <div className="mt-6">
          <SectionTitle hint="SP mới · SP trọng tâm">Tiến độ chương trình bán hàng</SectionTitle>
          <TableWrap>
            <thead>
              <tr>
                <th>Chương trình</th>
                <th>Loại</th>
                <th className="text-right">SL bán</th>
                <th className="text-right">Mục tiêu SL</th>
                <th style={{ width: 150 }}>Doanh thu / mục tiêu</th>
                <th className="text-right">Số KH mua</th>
                <th className="text-right">Số SKUs</th>
              </tr>
            </thead>
            <tbody>
              {programs.map((program) => (
                <tr key={program.id}>
                  <td className="font-medium text-ink-700">{program.name}</td>
                  <td>
                    <Badge tone={program.type === "NEW_PRODUCT" ? "gold" : "brand"}>
                      {
                        { NEW_PRODUCT: "SP mới", FOCUS_PRODUCT: "SP trọng tâm", CAMPAIGN: "Chiến dịch" }[
                          program.type
                        ]
                      }
                    </Badge>
                  </td>
                  <td className="tnum text-right">{formatNumber(program.qtySold)}</td>
                  <td className="tnum text-right text-ink-400">
                    {program.qtyTarget > 0 ? formatNumber(program.qtyTarget) : "—"}
                  </td>
                  <td>
                    <div className="tnum mb-1 flex justify-between text-xs text-ink-600">
                      <span className="font-semibold">{formatVndShort(program.revenue)}</span>
                      <span className="text-ink-400">
                        {program.revenueTarget > 0 ? formatVndShort(program.revenueTarget) : "—"}
                      </span>
                    </div>
                    {program.revenuePct != null && (
                      <ProgressBar percent={program.revenuePct} benchmark={primary.timePct} />
                    )}
                  </td>
                  <td className="tnum text-right text-ink-500">{program.customerCount}</td>
                  <td className="tnum text-right text-ink-500">{program.skuCount}</td>
                </tr>
              ))}
            </tbody>
          </TableWrap>
          <p className="mt-2 text-xs text-ink-400">
            Chương trình được gắn tự động vào dòng hàng theo danh sách sản phẩm đã khai báo, không phải
            chọn tay khi lên đơn.
          </p>
        </div>
      )}

      <div className="mt-6">
        <SectionTitle hint="15 sản phẩm dẫn đầu">Chi tiết theo mặt hàng</SectionTitle>
        <TableWrap>
          <thead>
            <tr>
              <th>Mã</th>
              <th>Sản phẩm</th>
              <th>Nhóm vai trò</th>
              <th className="text-right">SL bán</th>
              <th className="text-right">SL KM</th>
              <th className="text-right">Số KH mua</th>
              <th className="text-right">Doanh thu</th>
              <th className="text-right">Tỷ trọng</th>
            </tr>
          </thead>
          <tbody>
            {byProduct.length === 0 && (
              <tr>
                <td colSpan={8} className="py-8 text-center text-ink-400">
                  Không có dữ liệu trong kỳ.
                </td>
              </tr>
            )}
            {byProduct.map((row) => (
              <tr key={row.productId}>
                <td className="tnum text-ink-400">{row.code}</td>
                <td className="font-medium text-ink-700">{row.name}</td>
                <td>
                  <Badge tone={row.role === "CORE" ? "brand" : row.role === "RECOVERY" ? "red" : "neutral"}>
                    {{ CORE: "Chủ lực", POTENTIAL: "Tiềm năng", RECOVERY: "Khôi phục", NORMAL: "Thường" }[row.role]}
                  </Badge>
                </td>
                <td className="tnum text-right">{formatNumber(Number(row.qtySold))}</td>
                <td className="tnum text-right text-ink-400">{formatNumber(Number(row.qtyPromo))}</td>
                <td className="tnum text-right text-ink-500">{row.customerCount}</td>
                <td className="tnum text-right font-semibold">{formatVndShort(Number(row.revenue))}</td>
                <td className="tnum text-right text-ink-400">
                  {totalRevenue > 0 ? formatPercent((Number(row.revenue) / totalRevenue) * 100, 1) : "—"}
                </td>
              </tr>
            ))}
          </tbody>
        </TableWrap>
        <p className="mt-2 text-xs text-ink-400">
          Tỷ trọng tính trên tổng doanh thu của kỳ.
          {baseSession.role !== "SALES" && (
            <>
              {" "}Danh sách đầy đủ mọi sản phẩm, doanh số từng sản phẩm và biểu đồ ở{" "}
              <Link href={`/phan-tich?muc=san-pham&ky=${progressPeriod}${pvQuery}`} className="text-brand-600 hover:underline">
                Phân tích → Sản phẩm
              </Link>
              .
            </>
          )}
        </p>
      </div>

      {/* Ngân sách / hàng khuyến mãi đã sử dụng theo khu vực, phòng ban, nhân viên trong kỳ đang xem (tuần, tháng, quý, năm). */}
      {promo.totals.qty > 0 && (
        <div className="mt-6">
          <SectionTitle hint="giá trị hàng khuyến mãi = số lượng × đơn giá">Khuyến mãi đã sử dụng</SectionTitle>
          <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
            <StatCard label="Giá trị KM đã dùng" value={formatVndShort(promo.totals.value)} hint={formatVnd(promo.totals.value)} />
            <StatCard label="SL hàng KM" value={formatNumber(promo.totals.qty)} />
            <StatCard label="Doanh thu cùng kỳ" value={formatVndShort(promo.totals.revenue)} />
            <StatCard label="KM / doanh thu" value={promo.totals.ratioPct != null ? formatPercent(promo.totals.ratioPct, 1) : "—"} />
          </div>
          <PromoBreakdown promo={promo} />
        </div>
      )}

      {/* Hàng khuyến mãi theo NVKD — khách yêu cầu khi trả lời câu "ngân sách khuyến mãi":
          không có ngân sách, khuyến mãi luôn quy ra hàng, nên theo dõi NVKD nào đã cho đi
          bao nhiêu hàng KM, mặt hàng gì, tận dụng luôn 5 kỳ Ngày/Tuần/Tháng/Quý/Năm đã có. */}
      {byStaffPromo.length > 0 && (
        <div className="mt-6">
          <SectionTitle hint="theo Ngày/Tuần/Tháng/Quý/Năm đang xem">
            Hàng khuyến mãi theo NVKD
          </SectionTitle>
          <TableWrap>
            <thead>
              <tr>
                <th>Nhân viên</th>
                <th>Mã</th>
                <th>Sản phẩm</th>
                <th className="text-right">SL KM</th>
                <th className="text-right">Giá trị KM</th>
              </tr>
            </thead>
            <tbody>
              {byStaffPromo.map((row) => (
                <tr key={`${row.salesUserId ?? "none"}-${row.productId}`}>
                  <td className="font-medium text-ink-700">{row.salesUserName}</td>
                  <td className="tnum text-ink-400">{row.code}</td>
                  <td className="text-ink-600">{row.name}</td>
                  <td className="tnum text-right">{formatNumber(Number(row.qtyPromo))}</td>
                  <td className="tnum text-right font-medium">{formatVndShort(Number(row.promoValue))}</td>
                </tr>
              ))}
            </tbody>
          </TableWrap>
        </div>
      )}

      {/* Chuyên đề / lớp học — yêu cầu mục 4, báo cáo tuần */}
      <div className="mt-6">
        <SectionTitle hint={eventList.total > 0 ? `${eventList.total} lớp trong kỳ${eventList.total > events.length ? ` · hiện ${events.length} lớp mới nhất` : ""}` : undefined}>
          Tiến độ chuyên đề &amp; lớp học
        </SectionTitle>
        {events.length === 0 ? (
          <div className="card px-4 py-8 text-center text-sm text-ink-400">
            Không có chuyên đề hay lớp học nào trong kỳ này.
          </div>
        ) : (
          <>
            {/* Số lớp theo phân loại — NVKD Chuyên môn xem nhanh khối lượng đã dạy trong kỳ,
                không cần đếm tay trong bảng chi tiết bên dưới. */}
            <div className="mb-3 flex flex-wrap gap-1.5">
              {eventOverview.byKind.map((k) => (
                <Badge key={k.kind}>
                  {k.kind}: {k.classes}
                </Badge>
              ))}
            </div>
            <TableWrap>
            <thead>
              <tr>
                <th>Chuyên đề / lớp học</th>
                <th>Ngày</th>
                <th>Khu vực</th>
                <th className="text-right">Mời</th>
                <th className="text-right">Tham dự</th>
                <th className="text-right">Tỷ lệ dự</th>
                <th className="text-right">Đơn chốt</th>
                <th className="text-right">Doanh thu</th>
              </tr>
            </thead>
            <tbody>
              {events.map((event) => (
                <tr key={event.id}>
                  <td>
                    <div className="font-medium text-ink-700">{event.name}</div>
                    <div className="text-[11px] text-ink-400">
                      {event.kind}
                      {event.ownerName ? ` · ${event.ownerName}` : ""}
                    </div>
                  </td>
                  <td className="tnum whitespace-nowrap text-ink-500">{formatDate(event.eventDate)}</td>
                  <td className="text-ink-500">{event.territoryName ?? "—"}</td>
                  <td className="tnum text-right text-ink-500">{formatNumber(event.invitedCount)}</td>
                  <td className="tnum text-right font-medium">{formatNumber(event.attendedCount)}</td>
                  <td className="tnum text-right">
                    {event.attendanceRate != null ? (
                      <Badge tone={event.attendanceRate >= 60 ? "green" : event.attendanceRate >= 40 ? "gold" : "red"}>
                        {formatPercent(event.attendanceRate)}
                      </Badge>
                    ) : (
                      <span className="text-ink-300">—</span>
                    )}
                  </td>
                  <td className="tnum text-right text-ink-500">{formatNumber(event.resultOrderCount)}</td>
                  <td className="tnum text-right font-semibold">{formatVndShort(event.resultRevenue)}</td>
                </tr>
              ))}
            </tbody>
          </TableWrap>
          </>
        )}
        <p className="mt-2 text-xs text-ink-400">
          Biểu đồ số lớp theo loại lớp (ngày, tuần, tháng, quý, năm), theo khu vực / phòng ban / nhân viên và danh sách đầy đủ ở{" "}
          <Link href={`/bao-cao/chuyen-giao?ky=${tab}&ngay=${anchor}${pvQuery}`} className="text-brand-600 hover:underline">
            Báo cáo chuyển giao
          </Link>
          .
        </p>
      </div>

      {/* Khách hàng mở mới — yêu cầu mục 4: thông tin, kênh, trị giá đơn, số SP */}
      {newCustomers.length > 0 && (
        <div className="mt-6">
          <SectionTitle hint={`${newCustomers.length} khách mở mới${customerStats.ratioPct != null ? ` · ${formatPercent(customerStats.ratioPct, 1)} tổng ${formatNumber(customerStats.total)} khách` : ""}`}>
            Chi tiết khách hàng mở mới
          </SectionTitle>
          <TableWrap>
            <thead>
              <tr>
                <th>Khách hàng</th>
                <th>Kênh · Khu vực</th>
                <th>NVKD</th>
                <th>Trạng thái</th>
                <th className="text-right">Số đơn</th>
                <th className="text-right">Số SP</th>
                <th className="text-right">Trị giá đơn hàng</th>
              </tr>
            </thead>
            <tbody>
              {newCustomers.map((customer) => (
                <tr key={customer.id}>
                  <td>
                    <Link
                      href={`/khach-hang/${customer.id}`}
                      className="font-medium text-ink-700 hover:text-brand-600"
                    >
                      {customer.orgName}
                    </Link>
                    <div className="text-[11px] text-ink-400">
                      {customer.code}
                      {customer.contactName ? ` · ${customer.contactName}` : ""}
                      {customer.phone ? ` · ${customer.phone}` : ""}
                    </div>
                  </td>
                  <td className="text-ink-500">
                    <div>{customer.channelName ?? "—"}</div>
                    <div className="text-[11px] text-ink-400">{customer.territoryName ?? "—"}</div>
                  </td>
                  <td className="text-ink-500">{customer.ownerName ?? "—"}</td>
                  <td>
                    <Badge tone={customer.stage === "DEALER" ? "brand" : customer.stage === "PROSPECT" ? "gold" : "neutral"}>
                      {STAGE_LABEL[customer.stage]}
                    </Badge>
                  </td>
                  <td className="tnum text-right text-ink-500">{customer.orderCount || "—"}</td>
                  <td className="tnum text-right text-ink-500">{customer.skuCount || "—"}</td>
                  <td className="tnum text-right font-semibold">
                    {customer.revenue > 0 ? formatVndShort(customer.revenue) : "—"}
                  </td>
                </tr>
              ))}
            </tbody>
          </TableWrap>
          {baseSession.role !== "SALES" && (
            <p className="mt-2 text-xs text-ink-400">
              Khách mở mới theo khu vực, phòng ban, nhân viên và xếp hạng khách hàng theo doanh thu / doanh số / công nợ ở{" "}
              <Link href={`/phan-tich?muc=khach-hang&kh=moi&ky=${progressPeriod}${pvQuery}`} className="text-brand-600 hover:underline">
                Phân tích → Khách hàng
              </Link>
              .
            </p>
          )}
        </div>
      )}

      <div className="mt-6">
        <SectionTitle hint={`${dealers.inactive.length}/${dealers.total} đại lý không lấy hàng`}>
          Theo dõi đại lý lấy hàng so với data đang quản lý
        </SectionTitle>
        <TableWrap>
          <thead>
            <tr>
              <th>Đại lý</th>
              <th>Khu vực · NVKD</th>
              <th className="text-center">Phân loại</th>
              <th className="text-right">Số SP</th>
              <th className="text-right">Số đơn</th>
              <th className="text-right">Doanh thu</th>
              <th>Tình trạng</th>
              <th style={{ minWidth: 230 }}>Lý do không lấy hàng</th>
            </tr>
          </thead>
          <tbody>
            {[...dealers.active, ...dealers.inactive].slice(0, 60).map((dealer) => (
              <tr key={dealer.id}>
                <td>
                  <Link href={`/khach-hang/${dealer.id}`} className="font-medium text-ink-700 hover:text-brand-600">
                    {dealer.orgName}
                  </Link>
                  <div className="text-[11px] text-ink-400">
                    {dealer.code}
                    {dealer.isKey ? " · ĐL Key" : ""}
                  </div>
                </td>
                <td className="text-ink-500">
                  <div>{dealer.territoryName ?? "—"}</div>
                  <div className="text-[11px] text-ink-400">{dealer.ownerName ?? "—"}</div>
                </td>
                <td className="text-center">
                  <TierBadge tier={dealer.revenueTier} />
                </td>
                <td className="tnum text-right text-ink-500">{dealer.skuCount || "—"}</td>
                <td className="tnum text-right text-ink-500">{dealer.orderCount || "—"}</td>
                <td className="tnum text-right">
                  {dealer.revenue > 0 ? formatVndShort(dealer.revenue) : "—"}
                </td>
                <td>
                  {dealer.orderCount > 0 ? (
                    <Badge tone="green">Có lấy hàng</Badge>
                  ) : (
                    <div className="flex flex-col gap-1">
                      <Badge tone="red">Không lấy hàng</Badge>
                      {dealer.monthsInactive > 1 && (
                        <span className="text-[11px] text-ink-400">{dealer.monthsInactive} tháng liền</span>
                      )}
                    </div>
                  )}
                </td>
                <td>
                  {dealer.orderCount > 0 ? (
                    <span className="text-ink-300">—</span>
                  ) : (
                    /* Ô nhập ngay trên bảng: quản lý đang rà danh sách thì ghi được luôn,
                       không phải mở từng hồ sơ khách hàng. */
                    <ActionForm action={saveInactiveReasonAction} success="Đã lưu lý do." className="flex items-center gap-1">
                      <input type="hidden" name="customerId" value={dealer.id} />
                      <input type="hidden" name="periodKey" value={dealers.periodKey} />
                      <input
                        name="reason"
                        defaultValue={dealer.reason ?? ""}
                        maxLength={300}
                        placeholder="Ghi lý do…"
                        aria-label={`Lý do ${dealer.orgName} không lấy hàng`}
                        className="input w-full py-1 text-sm"
                      />
                      <button type="submit" className="btn-ghost px-2 py-1 text-xs">
                        Lưu
                      </button>
                    </ActionForm>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </TableWrap>
        <p className="mt-2 text-xs text-ink-400">
          Lý do được lưu theo từng kỳ, nên tháng sau đại lý vẫn im lặng thì phải ghi lý do mới — đó
          chính là thông tin cần: lý do có đổi hay vẫn thế.
        </p>
      </div>
    </>
  );
}
