import Link from "next/link";
import { requireSession } from "@/lib/auth";
import { FocusSelect } from "@/components/focus-select";
import { loadFocusOptions, parseFocus, withFocus } from "@/lib/focus";
import { courseCompletions, transferByGroup, transferList, transferOverview, transferTrend, type TrendGranularity } from "@/lib/transfer-report";
import { orderKinds } from "@/lib/event-kinds";
import { isRealDate, monthKey, periodRange, quarterOfMonth, today, weekDays, weekStart } from "@/lib/period";
import { formatDate, formatNumber, formatPercent, formatVndShort } from "@/lib/format";
import { Badge, EmptyState, PageHeader, SectionTitle, StatCard, TableWrap } from "@/components/ui";
import { ShareChart, StackedKindChart } from "@/components/charts";
import { kindColors } from "@/lib/chart-colors";

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" },
];
const DIMENSIONS = [
  { key: "khu-vuc", label: "Khu vực" },
  { key: "phong-ban", label: "Phòng ban / Team" },
  { key: "nhan-vien", label: "Nhân viên" },
] as const;
type Dimension = (typeof DIMENSIONS)[number]["key"];

const TREND_HINT: Record<Tab, string> = {
  ngay: "7 ngày tính đến ngày đang xem",
  tuan: "từng ngày trong tuần",
  thang: "từng tuần trong tháng (ngày đầu–ngày cuối tuần)",
  quy: "từng tháng trong quý",
  nam: "từng tháng trong năm",
};

const tree = (name: string, depth: number) => (
  <span style={{ paddingLeft: depth * 18 }} className={depth === 0 ? "font-semibold text-ink-700" : "text-ink-600"}>
    {depth > 0 && <span className="mr-1 text-ink-300">└</span>}
    {name}
  </span>
);

/**
 * Báo cáo chuyển giao: số lớp theo loại lớp theo ngày / tuần / tháng / quý / năm, theo toàn công ty, khu vực, phòng ban / team hoặc nhân viên.
 * Cùng bộ tab kỳ và ô "Phạm vi xem" với trang Báo cáo bán hàng.
 */
export default async function TransferReportPage({ searchParams }: { searchParams: Promise<{ ky?: string; ngay?: string; pv?: string; dv?: string; trang?: 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.
  const anchor = isRealDate(params.ngay) ? params.ngay : today();
  const dimension: Dimension = DIMENSIONS.find((d) => d.key === params.dv)?.key ?? "khu-vuc";
  const pageParam = Number(params.trang);
  const wantedPage = Number.isInteger(pageParam) && pageParam >= 1 && pageParam <= 10_000 ? pageParam : 1;

  const monthPeriod = monthKey(anchor);
  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(quarterOfMonth(monthPeriod))
          : tab === "nam"
            ? periodRange(anchor.slice(0, 4))
            : periodRange(monthPeriod);

  const granularity: TrendGranularity = tab;
  const [overview, trend, groups, list, courses] = await Promise.all([
    transferOverview(session, range),
    transferTrend(session, range, granularity),
    transferByGroup(session, range, dimension),
    transferList(session, range, { page: wantedPage }),
    courseCompletions(session, range),
  ]);

  const kinds = orderKinds([...overview.byKind.map((k) => k.kind), ...trend.kinds]);
  const colors = kindColors(kinds);
  const { totals } = overview;

  const href = (patch: Record<string, string> = {}) => {
    const next: Record<string, string> = { ky: tab, ngay: anchor, ...(pvValue ? { pv: pvValue } : {}), ...(dimension !== "khu-vuc" ? { dv: dimension } : {}), ...patch };
    const qs = new URLSearchParams();
    for (const [key, value] of Object.entries(next)) if (value) qs.set(key, value);
    return `/bao-cao/chuyen-giao?${qs.toString()}`;
  };

  return (
    <>
      <PageHeader
        title="Báo cáo chuyển giao"
        subtitle={`Các loại lớp · từ ${formatDate(range.start)} đến ${formatDate(range.end)}`}
        actions={
          <>
            <Link href={`/bao-cao?ky=${tab}&ngay=${anchor}${pvQuery}`} className="btn-ghost">
              ← Báo cáo bán hàng
            </Link>
            <a href={`/api/xuat-excel?loai=chuyen-giao&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/chuyen-giao">
        <div className="flex gap-1 rounded-lg border border-[var(--color-line)] bg-white p-1">
          {TABS.map((item) => (
            <Link key={item.key} href={href({ ky: item.key, trang: "" })} 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} />
        {dimension !== "khu-vuc" && <input type="hidden" name="dv" value={dimension} />}
        <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-6">
        <StatCard label="Số lớp" value={formatNumber(totals.classes)} hint={`${formatNumber(totals.owners)} người phụ trách`} />
        <StatCard label="Lượt mời" value={formatNumber(totals.invited)} />
        <StatCard label="Lượt tham dự" value={formatNumber(totals.attended)} hint={totals.ratePct != null ? `${formatPercent(totals.ratePct)} lượt mời` : undefined} tone={totals.ratePct != null && totals.ratePct >= 60 ? "good" : "default"} />
        <StatCard label="Đơn chốt sau lớp" value={formatNumber(totals.orders)} />
        <StatCard label="Doanh thu sau lớp" value={formatVndShort(totals.revenue)} />
        <StatCard label="Khách hoàn thành khóa" value={formatNumber(courses.totalCustomers)} hint={`${formatNumber(courses.totalCompletions)} lượt hoàn thành`} />
      </div>

      {totals.classes === 0 && (
        <div className="mt-5">
          <EmptyState message="Không có lớp hay chuyên đề nào trong kỳ này." hint="Lớp được ghi ở Danh mục → Chuyên đề & lớp học (nhân viên chuyên môn tự ghi ở Công việc → Ghi lớp chuyển giao)." />
        </div>
      )}

      {(totals.classes > 0 || trend.buckets.some((b) => b.total > 0)) && (
        <div className="mt-5 grid gap-4 lg:grid-cols-3">
          <div className="card p-4">
            <SectionTitle hint="tỷ trọng số lớp">Các loại lớp</SectionTitle>
            <ShareChart data={overview.byKind.map((k) => ({ name: k.kind, value: k.classes }))} max={8} unit="count" colors={colors} />
          </div>
          <div className="card p-4 lg:col-span-2">
            <SectionTitle hint={TREND_HINT[tab]}>Số lớp theo loại</SectionTitle>
            <StackedKindChart
              data={trend.buckets.map((b) => ({ label: b.label, ...Object.fromEntries(kinds.map((k) => [k, b.byKind[k] ?? 0])) }))}
              kinds={kinds}
              colors={colors}
            />
          </div>
        </div>
      )}

      {overview.byKind.length > 0 && (
        <div className="mt-6">
          <SectionTitle hint="trong kỳ đang xem">Theo loại lớp</SectionTitle>
          <TableWrap>
            <thead>
              <tr>
                <th>Loại lớp</th>
                <th className="text-right">Số lớp</th>
                <th className="text-right">Tỷ trọng</th>
                <th className="text-right">Lượt mời</th>
                <th className="text-right">Lượt 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>
              {overview.byKind.map((k) => (
                <tr key={k.kind}>
                  <td>
                    <span className="mr-2 inline-block h-2.5 w-2.5 rounded-full align-middle" style={{ background: colors[k.kind] }} />
                    <span className="font-medium text-ink-700">{k.kind}</span>
                  </td>
                  <td className="tnum text-right font-semibold">{k.classes}</td>
                  <td className="tnum text-right text-ink-400">{formatPercent(k.sharePct, 1)}</td>
                  <td className="tnum text-right text-ink-500">{formatNumber(k.invited)}</td>
                  <td className="tnum text-right">{formatNumber(k.attended)}</td>
                  <td className="tnum text-right text-ink-500">{k.ratePct != null ? formatPercent(k.ratePct) : "—"}</td>
                  <td className="tnum text-right text-ink-500">{k.orders || "—"}</td>
                  <td className="tnum text-right font-medium">{k.revenue > 0 ? formatVndShort(k.revenue) : "—"}</td>
                </tr>
              ))}
              <tr className="border-t-2 border-[var(--color-line)] font-semibold">
                <td>Tổng cộng</td>
                <td className="tnum text-right">{totals.classes}</td>
                <td className="tnum text-right">100%</td>
                <td className="tnum text-right">{formatNumber(totals.invited)}</td>
                <td className="tnum text-right">{formatNumber(totals.attended)}</td>
                <td className="tnum text-right">{totals.ratePct != null ? formatPercent(totals.ratePct) : "—"}</td>
                <td className="tnum text-right">{totals.orders || "—"}</td>
                <td className="tnum text-right">{totals.revenue > 0 ? formatVndShort(totals.revenue) : "—"}</td>
              </tr>
            </tbody>
          </TableWrap>
        </div>
      )}

      {groups.length > 0 && (
        <div className="mt-6">
          <SectionTitle hint="số lớp và lượt tham dự của từng nhóm">Theo {DIMENSIONS.find((d) => d.key === dimension)!.label.toLowerCase()}</SectionTitle>
          <div className="mb-3 flex w-fit flex-wrap gap-1 rounded-lg border border-[var(--color-line)] bg-white p-1">
            {DIMENSIONS.map((d) => (
              <Link key={d.key} href={href({ dv: d.key === "khu-vuc" ? "" : d.key, trang: "" })} className={`rounded-md px-3 py-1.5 text-sm font-semibold ${dimension === d.key ? "bg-ink-700 text-white" : "text-ink-500 hover:bg-ink-50"}`}>
                {d.label}
              </Link>
            ))}
          </div>
          <TableWrap>
            <thead>
              <tr>
                <th>{DIMENSIONS.find((d) => d.key === dimension)!.label}</th>
                <th className="text-right">Số lớp</th>
                <th className="text-right">Lượt mời</th>
                <th className="text-right">Lượt 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>
              {groups.map((g) => (
                <tr key={g.id}>
                  <td>{dimension === "nhan-vien" && g.id !== "none" ? <Link href={`/danh-muc/nguoi-dung/${g.id}?ky=${tab === "ngay" ? "ngay" : tab}&ngay=${anchor}`} className="font-medium text-ink-700 hover:text-brand-600">{g.name}</Link> : tree(g.name, g.depth)}</td>
                  <td className="tnum text-right font-semibold">{g.classes}</td>
                  <td className="tnum text-right text-ink-500">{formatNumber(g.invited)}</td>
                  <td className="tnum text-right">{formatNumber(g.attended)}</td>
                  <td className="tnum text-right text-ink-500">{g.ratePct != null ? formatPercent(g.ratePct) : "—"}</td>
                  <td className="tnum text-right text-ink-500">{g.orders || "—"}</td>
                  <td className="tnum text-right font-medium">{g.revenue > 0 ? formatVndShort(g.revenue) : "—"}</td>
                </tr>
              ))}
            </tbody>
          </TableWrap>
        </div>
      )}

      {list.total > 0 && (
        <div className="mt-6">
          <SectionTitle hint={`${formatNumber(list.total)} lớp trong kỳ`}>Danh sách lớp</SectionTitle>
          <div className="flex flex-col gap-2 lg:hidden">
            {list.rows.map((c) => (
              <div key={c.id} className="card p-3.5">
                <div className="flex items-start justify-between gap-2">
                  <div className="min-w-0 font-medium text-ink-700">{c.name}</div>
                  <Badge>{c.kind}</Badge>
                </div>
                <div className="mt-1 text-[11px] text-ink-400">
                  {formatDate(c.eventDate)} · {c.territoryName ?? "Toàn quốc"} · {c.ownerName ?? "chưa phân công"}
                </div>
                <div className="mt-1.5 text-xs text-ink-500">
                  Mời {c.invitedCount} · dự <b className="text-ink-700">{c.attendedCount}</b>
                  {c.attendanceRate != null ? ` (${formatPercent(c.attendanceRate)})` : ""} · {c.resultOrderCount} đơn{c.resultRevenue > 0 ? ` · ${formatVndShort(c.resultRevenue)}` : ""}
                </div>
                {c.note && <p className="mt-1.5 text-xs text-ink-500">{c.note}</p>}
              </div>
            ))}
          </div>
          <div className="hidden lg:block">
            <TableWrap>
              <thead>
                <tr>
                  <th>Ngày</th>
                  <th>Lớp / chuyên đề</th>
                  <th>Loại</th>
                  <th>Khu vực</th>
                  <th>Người phụ trách</th>
                  <th className="text-right">Mời</th>
                  <th className="text-right">Dự</th>
                  <th className="text-right">Tỷ lệ dự</th>
                  <th className="text-right">Đơn</th>
                  <th className="text-right">Doanh thu</th>
                  <th style={{ minWidth: 240 }}>Ghi chú sau lớp</th>
                </tr>
              </thead>
              <tbody>
                {list.rows.map((c) => (
                  <tr key={c.id} className="align-top">
                    <td className="tnum whitespace-nowrap text-ink-500">{formatDate(c.eventDate)}</td>
                    <td className="font-medium text-ink-700">{c.name}</td>
                    <td>
                      <Badge>{c.kind}</Badge>
                    </td>
                    <td className="text-ink-500">{c.territoryName ?? "Toàn quốc"}</td>
                    <td className="text-ink-500">{c.ownerId ? <Link href={`/danh-muc/nguoi-dung/${c.ownerId}?ky=${tab}&ngay=${anchor}`} className="hover:text-brand-600">{c.ownerName}</Link> : "—"}</td>
                    <td className="tnum text-right text-ink-500">{c.invitedCount}</td>
                    <td className="tnum text-right font-medium">{c.attendedCount}</td>
                    <td className="tnum text-right text-ink-500">{c.attendanceRate != null ? formatPercent(c.attendanceRate) : "—"}</td>
                    <td className="tnum text-right text-ink-500">{c.resultOrderCount || "—"}</td>
                    <td className="tnum text-right font-medium">{c.resultRevenue > 0 ? formatVndShort(c.resultRevenue) : "—"}</td>
                    <td className="text-sm text-ink-500">{c.note || "—"}</td>
                  </tr>
                ))}
              </tbody>
            </TableWrap>
          </div>
          {list.totalPages > 1 && (
            <nav className="mt-4 flex items-center justify-center gap-3 text-sm" aria-label="Phân trang">
              {list.page > 1 ? (
                <Link href={href({ trang: String(list.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 {list.page}/{list.totalPages} · {formatNumber(list.total)} lớp
              </span>
              {list.page < list.totalPages ? (
                <Link href={href({ trang: String(list.page + 1) })} className="btn-ghost">
                  Sau →
                </Link>
              ) : (
                <span className="btn-ghost pointer-events-none opacity-40">Sau →</span>
              )}
            </nav>
          )}
        </div>
      )}

      {courses.rows.length > 0 && (
        <div className="mt-6">
          <SectionTitle hint="khách trong phạm vi của bạn">Khách hoàn thành khóa chuyển giao</SectionTitle>
          <TableWrap>
            <thead>
              <tr>
                <th>Khóa chuyển giao</th>
                <th className="text-right">Lượt hoàn thành</th>
                <th className="text-right">Số khách</th>
                <th className="text-right">Học miễn phí</th>
              </tr>
            </thead>
            <tbody>
              {courses.rows.map((c) => (
                <tr key={c.courseId}>
                  <td className="font-medium text-ink-700">{c.name}</td>
                  <td className="tnum text-right font-semibold">{c.completions}</td>
                  <td className="tnum text-right text-ink-500">{c.customers}</td>
                  <td className="tnum text-right text-ink-500">{c.free || "—"}</td>
                </tr>
              ))}
            </tbody>
          </TableWrap>
        </div>
      )}

      <p className="mt-6 text-xs text-ink-400">
        Số lớp tính theo ngày tổ chức. Loại lớp là loại chọn khi ghi lớp (Lớp sản phẩm, Lớp quy trình, Chuyển giao tại cơ sở khách, Báo cáo Hội nghị/Bệnh viện, Chuyên đề, Lớp học, Hội thảo…). Quản lý chỉ thấy lớp do nhân viên trong nhánh của mình phụ trách.
      </p>
    </>
  );
}
