import Link from "next/link";
import { requireSession } from "@/lib/auth";
import { withFocus } from "@/lib/focus";
import {
  coreMetrics,
  revenueByTerritory,
  revenueBySalesUser,
  revenueByProduct,
  dealerActivity,
  targetFor,
  programProgress,
} from "@/lib/reports";
import { periodRange, monthKey, today, monthProgress, isRealDate } from "@/lib/period";
import { formatVnd, formatNumber, formatPercent, formatDate } from "@/lib/format";
import { PrintButton } from "./print-button";

export const dynamic = "force-dynamic";

/**
 * Bản in của báo cáo bán hàng.
 *
 * Xuất PDF đi qua chức năng in của trình duyệt thay vì sinh PDF ở máy chủ. Lý do
 * thực dụng: mọi thư viện PDF thuần JavaScript đều phải nhúng font riêng mới hiển
 * thị được dấu tiếng Việt, kéo theo chuyện giấy phép font và kích thước gói cài;
 * còn Puppeteer thì phải tải kèm cả một trình duyệt Chromium. Trình duyệt của
 * người dùng đã có sẵn font tiếng Việt và làm việc này hoàn hảo.
 *
 * Nếu về sau khách cần PDF sinh tự động ở máy chủ để đính kèm email, lúc đó mới
 * thêm Puppeteer và render đúng trang này.
 */
export default async function PrintReportPage({
  searchParams,
}: {
  searchParams: Promise<{ tu?: string; den?: string; pv?: string }>;
}) {
  const params = await searchParams;
  const session = withFocus(await requireSession(), params.pv);
  const defaults = periodRange(monthKey(today()));
  // Ngày gõ trên đường dẫn phải có thật (sai thì lấy tháng hiện tại) và khoảng ngày không được ngược.
  const start = isRealDate(params.tu) ? params.tu : defaults.start;
  const end = isRealDate(params.den) ? params.den : defaults.end;
  const range = start <= end ? { start, end } : { start: end, end: start };
  // Chỉ tiêu đối chiếu là của THÁNG CHỨA khoảng ngày đang in (trước đây luôn lấy tháng hiện tại nên in báo cáo tháng cũ bị so với chỉ tiêu sai).
  const period = monthKey(range.end);

  const cutoff = range.end > today() ? today() : range.end;
  const monthStart = periodRange(period).start;
  const [metrics, byTerritory, bySales, byProduct, dealers, target, programs, monthToDate] = await Promise.all([
    coreMetrics(session, range),
    revenueByTerritory(session, range),
    revenueBySalesUser(session, range),
    revenueByProduct(session, range, 25),
    dealerActivity(session, range),
    targetFor(session, period),
    programProgress(session, range),
    // Tỷ lệ hoàn thành so với chỉ tiêu THÁNG phải dùng doanh thu luỹ kế từ đầu tháng, không phải riêng khoảng ngày đang in.
    coreMetrics(session, { start: monthStart, end: cutoff < monthStart ? monthStart : cutoff }),
  ]);

  const { elapsed, total } = monthProgress(period, cutoff);
  const totalRevenue = byTerritory.reduce((sum, r) => sum + Number(r.revenue), 0);
  const achievement =
    target && target.revenueTarget > 0 ? (monthToDate.revenue / target.revenueTarget) * 100 : null;

  return (
    <div className="print-report mx-auto max-w-4xl">
      <div className="mb-6 flex items-center justify-between gap-3 print:hidden">
        <Link href="/bao-cao" className="btn-ghost">
          ← Về báo cáo
        </Link>
        <PrintButton />
      </div>

      <div className="rounded-xl border border-[var(--color-line)] bg-white p-8 print:border-0 print:p-0">
        {/* Đầu trang */}
        <header className="mb-6 border-b border-[var(--color-line)] pb-4">
          <h1 className="text-xl font-bold text-ink-700">BÁO CÁO BÁN HÀNG</h1>
          <p className="mt-1 text-sm text-ink-500">{session.tenantName}</p>
          <p className="tnum mt-0.5 text-sm text-ink-500">
            Kỳ báo cáo: {formatDate(range.start)} – {formatDate(range.end)}
          </p>
          <p className="mt-0.5 text-xs text-ink-400">
            Người xem: {session.fullName} · Lập ngày {formatDate(today())}
          </p>
        </header>

        {/* Chỉ số tổng hợp */}
        <section className="mb-6">
          <h2 className="mb-2 text-sm font-bold uppercase tracking-wide text-ink-600">
            I. Chỉ số tổng hợp
          </h2>
          <table className="w-full text-sm">
            <tbody>
              {[
                ["Doanh thu thực hiện", formatVnd(metrics.revenue)],
                ["Chỉ tiêu tháng", target ? formatVnd(target.revenueTarget) : "Chưa giao"],
                ["Tỷ lệ hoàn thành (luỹ kế tháng)", achievement != null ? formatPercent(achievement) : "—"],
                ["Tiến độ thời gian", `${elapsed}/${total} ngày (${formatPercent((elapsed / total) * 100)})`],
                ["Số đơn hàng", formatNumber(metrics.orderCount)],
                ["Số SKUs đã bán", formatNumber(metrics.skuCount)],
                ["Số đại lý lấy hàng", `${dealers.active.length}/${dealers.total}`],
                ["Khách hàng mở mới", formatNumber(metrics.newCustomerCount)],
                ["Giá trị hàng khuyến mãi", formatVnd(metrics.promoValue)],
              ].map(([label, value]) => (
                <tr key={label} className="border-b border-[var(--color-line)]">
                  <td className="py-1.5 text-ink-500">{label}</td>
                  <td className="tnum py-1.5 text-right font-semibold text-ink-700">{value}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </section>

        {/* Khu vực */}
        <section className="mb-6 break-inside-avoid">
          <h2 className="mb-2 text-sm font-bold uppercase tracking-wide text-ink-600">
            II. Doanh thu theo khu vực
          </h2>
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b-2 border-ink-200">
                <th className="py-1.5 text-left font-semibold text-ink-600">Khu vực</th>
                <th className="py-1.5 text-right font-semibold text-ink-600">Số đơn</th>
                <th className="py-1.5 text-right font-semibold text-ink-600">Số KH</th>
                <th className="py-1.5 text-right font-semibold text-ink-600">Doanh thu</th>
                <th className="py-1.5 text-right font-semibold text-ink-600">Tỷ trọng</th>
              </tr>
            </thead>
            <tbody>
              {byTerritory.map((row) => (
                <tr key={row.territoryId ?? "none"} className="border-b border-[var(--color-line)]">
                  <td className="py-1.5 text-ink-700">{row.territoryName}</td>
                  <td className="tnum py-1.5 text-right">{row.orderCount}</td>
                  <td className="tnum py-1.5 text-right">{row.customerCount}</td>
                  <td className="tnum py-1.5 text-right font-medium">{formatVnd(Number(row.revenue))}</td>
                  <td className="tnum py-1.5 text-right text-ink-500">
                    {totalRevenue > 0 ? formatPercent((Number(row.revenue) / totalRevenue) * 100, 1) : "—"}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </section>

        {/* NVKD */}
        <section className="mb-6 break-inside-avoid">
          <h2 className="mb-2 text-sm font-bold uppercase tracking-wide text-ink-600">
            III. Doanh thu theo nhân viên kinh doanh
          </h2>
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b-2 border-ink-200">
                <th className="py-1.5 text-left font-semibold text-ink-600">Nhân viên</th>
                <th className="py-1.5 text-right font-semibold text-ink-600">Số đơn</th>
                <th className="py-1.5 text-right font-semibold text-ink-600">Số KH</th>
                <th className="py-1.5 text-right font-semibold text-ink-600">Doanh thu</th>
              </tr>
            </thead>
            <tbody>
              {bySales.map((row) => (
                <tr key={row.userId ?? "none"} className="border-b border-[var(--color-line)]">
                  <td className="py-1.5 text-ink-700">{row.fullName}</td>
                  <td className="tnum py-1.5 text-right">{row.orderCount}</td>
                  <td className="tnum py-1.5 text-right">{row.customerCount}</td>
                  <td className="tnum py-1.5 text-right font-medium">{formatVnd(Number(row.revenue))}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </section>

        {/* Chương trình */}
        {programs.length > 0 && (
          <section className="mb-6 break-inside-avoid">
            <h2 className="mb-2 text-sm font-bold uppercase tracking-wide text-ink-600">
              IV. Tiến độ chương trình bán hàng
            </h2>
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b-2 border-ink-200">
                  <th className="py-1.5 text-left font-semibold text-ink-600">Chương trình</th>
                  <th className="py-1.5 text-right font-semibold text-ink-600">SL bán</th>
                  <th className="py-1.5 text-right font-semibold text-ink-600">Doanh thu</th>
                  <th className="py-1.5 text-right font-semibold text-ink-600">% Mục tiêu</th>
                </tr>
              </thead>
              <tbody>
                {programs.map((program) => (
                  <tr key={program.id} className="border-b border-[var(--color-line)]">
                    <td className="py-1.5 text-ink-700">{program.name}</td>
                    <td className="tnum py-1.5 text-right">{formatNumber(program.qtySold)}</td>
                    <td className="tnum py-1.5 text-right font-medium">{formatVnd(program.revenue)}</td>
                    <td className="tnum py-1.5 text-right">
                      {program.revenuePct != null ? formatPercent(program.revenuePct) : "—"}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </section>
        )}

        {/* Mặt hàng */}
        <section className="mb-6">
          <h2 className="mb-2 text-sm font-bold uppercase tracking-wide text-ink-600">
            V. Chi tiết theo mặt hàng
          </h2>
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b-2 border-ink-200">
                <th className="py-1.5 text-left font-semibold text-ink-600">Mã</th>
                <th className="py-1.5 text-left font-semibold text-ink-600">Sản phẩm</th>
                <th className="py-1.5 text-right font-semibold text-ink-600">SL bán</th>
                <th className="py-1.5 text-right font-semibold text-ink-600">SL KM</th>
                <th className="py-1.5 text-right font-semibold text-ink-600">Doanh thu</th>
              </tr>
            </thead>
            <tbody>
              {byProduct.map((row) => (
                <tr key={row.productId} className="border-b border-[var(--color-line)]">
                  <td className="tnum py-1.5 text-ink-400">{row.code}</td>
                  <td className="py-1.5 text-ink-700">{row.name}</td>
                  <td className="tnum py-1.5 text-right">{formatNumber(Number(row.qtySold))}</td>
                  <td className="tnum py-1.5 text-right text-ink-500">{formatNumber(Number(row.qtyPromo))}</td>
                  <td className="tnum py-1.5 text-right font-medium">{formatVnd(Number(row.revenue))}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </section>

        {/* Đại lý chưa lấy hàng */}
        {dealers.inactive.length > 0 && (
          <section className="mb-6">
            <h2 className="mb-2 text-sm font-bold uppercase tracking-wide text-ink-600">
              VI. Đại lý chưa lấy hàng trong kỳ ({dealers.inactive.length}/{dealers.total})
            </h2>
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b-2 border-ink-200">
                  <th className="py-1.5 text-left font-semibold text-ink-600">Mã</th>
                  <th className="py-1.5 text-left font-semibold text-ink-600">Đại lý</th>
                  <th className="py-1.5 text-left font-semibold text-ink-600">Khu vực</th>
                  <th className="py-1.5 text-left font-semibold text-ink-600">NVKD phụ trách</th>
                </tr>
              </thead>
              <tbody>
                {dealers.inactive.map((dealer) => (
                  <tr key={dealer.id} className="border-b border-[var(--color-line)]">
                    <td className="tnum py-1.5 text-ink-400">{dealer.code}</td>
                    <td className="py-1.5 text-ink-700">{dealer.orgName}</td>
                    <td className="py-1.5 text-ink-500">{dealer.territoryName ?? "—"}</td>
                    <td className="py-1.5 text-ink-500">{dealer.ownerName ?? "—"}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </section>
        )}

        {/* Chữ ký */}
        <footer className="mt-10 grid grid-cols-2 gap-8 break-inside-avoid text-center text-sm">
          <div>
            <div className="font-semibold text-ink-700">Người lập báo cáo</div>
            <div className="text-xs text-ink-400">(Ký, ghi rõ họ tên)</div>
            <div className="mt-16 text-ink-700">{session.fullName}</div>
          </div>
          <div>
            <div className="font-semibold text-ink-700">Ban giám đốc</div>
            <div className="text-xs text-ink-400">(Ký, ghi rõ họ tên)</div>
          </div>
        </footer>
      </div>
    </div>
  );
}
