import { ActionForm } from "@/components/action-form";
import Link from "next/link";
import { notFound } from "next/navigation";
import { and, eq, inArray } from "drizzle-orm";
import { requireSession } from "@/lib/auth";
import { db } from "@/db";
import { territories } from "@/db/schema";
import { getInviteEventDetail, inviteScopeUserIds } from "@/lib/invite-events";
import { formatDate, formatNumber, formatPercent } from "@/lib/format";
import { PageHeader, StatCard, TableWrap, SectionTitle, ProgressBar, EmptyState, Badge } from "@/components/ui";
import { setTerritoryQuotaAction, setDeptQuotaAction, setStaffQuotaAction } from "../actions";
import { AddGuestForm, AddGuestBatchForm, GuestList } from "./guest-client";
import { idOr404 } from "@/lib/route-params";

export const dynamic = "force-dynamic";

/** Ô nhập chỉ tiêu gọn (số + nút Lưu) dùng chung cho 3 cấp. */
function QuotaInput({ action, hidden, defaultValue, success }: { action: (formData: FormData) => Promise<unknown>; hidden: Record<string, string>; defaultValue: number; success: string }) {
  return (
    <ActionForm action={action} success={success} className="flex items-center justify-end gap-1">
      {Object.entries(hidden).map(([name, value]) => (
        <input key={name} type="hidden" name={name} value={value} />
      ))}
      <input name="quota" type="number" min={0} defaultValue={defaultValue} className="input w-20 py-1 text-right" aria-label="Chỉ tiêu" />
      <button type="submit" className="btn-ghost px-2 py-1 text-xs">
        Lưu
      </button>
    </ActionForm>
  );
}

export default async function InviteEventDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const session = await requireSession();
  const id = idOr404((await params).id);

  const detail = await getInviteEventDetail(session, id);
  if (!detail) notFound();

  const {
    event, deadline, daysLeft, perDayNeeded, quotaLabel, quotaTotal, invitedTotal, attendedTotal, decidedTotal,
    territoryQuotas, deptQuotas, staffQuotas, guests, byType, byDay, canSetTerritoryQuota,
    assignableDepartments, canSetDeptQuotaIds, assignableStaff, canSetStaffQuotaIds, myAssignedTerritoryIds,
  } = detail;

  // Miền chưa có chỉ tiêu — để TGĐ thêm mới.
  const allRegions = await db
    .select({ id: territories.id, name: territories.name })
    .from(territories)
    .where(and(eq(territories.tenantId, session.tenantId), eq(territories.level, "REGION")));
  const quotaedRegionIds = new Set(territoryQuotas.map((r) => r.territoryId));
  const regionsWithoutQuota = canSetTerritoryQuota ? allRegions.filter((r) => !quotaedRegionIds.has(r.id)) : [];

  // Khu vực để chọn khi ghi nhận khách mời.
  let guestTerritoryOptions: { id: string; name: string }[] = [];
  if (session.role === "SALES") {
    if (session.territoryId) {
      const [row] = await db.select({ id: territories.id, name: territories.name }).from(territories).where(and(eq(territories.tenantId, session.tenantId), eq(territories.id, session.territoryId))).limit(1);
      if (row) guestTerritoryOptions = [row];
    }
  } else if (session.role === "DIRECTOR") {
    guestTerritoryOptions = allRegions;
  } else if (myAssignedTerritoryIds.length > 0) {
    guestTerritoryOptions = await db
      .select({ id: territories.id, name: territories.name })
      .from(territories)
      .where(and(eq(territories.tenantId, session.tenantId), inArray(territories.id, myAssignedTerritoryIds)));
  }

  // Người mà người xem được sửa/xoá khách mời của họ (Ban giám đốc: mọi người).
  const manageableInviters = session.role === "DIRECTOR" ? null : session.role === "SALES" ? [session.userId] : await inviteScopeUserIds(session);

  const pct = quotaTotal > 0 ? (invitedTotal / quotaTotal) * 100 : null;
  const showTerritoryTable = session.role === "DIRECTOR" || session.role === "GDKV";
  const deadlineText = daysLeft > 0 ? `còn ${daysLeft} ngày` : daysLeft === 0 ? "hôm nay là hạn chót" : `đã quá hạn ${-daysLeft} ngày`;

  return (
    <>
      <PageHeader
        title={event.name}
        subtitle={`Diễn ra ${formatDate(event.eventDate)} · hạn chót mời khách ${formatDate(deadline)} (${deadlineText})${event.note ? ` · ${event.note}` : ""}`}
        actions={
          <Link href="/danh-muc/su-kien-moi-khach" className="btn-ghost">
            ← Sự kiện mời khách
          </Link>
        }
      />

      <div className="grid grid-cols-2 gap-3 lg:grid-cols-3 xl:grid-cols-6">
        <StatCard label={quotaLabel} value={formatNumber(quotaTotal)} />
        <StatCard label="Đã mời" value={formatNumber(invitedTotal)} hint={quotaTotal > 0 ? `còn thiếu ${formatNumber(Math.max(0, quotaTotal - invitedTotal))}` : undefined} />
        <StatCard label="% đạt chỉ tiêu" value={pct != null ? formatPercent(pct) : "—"} tone={pct == null ? "default" : pct >= 100 ? "good" : "default"} />
        <StatCard
          label="Cần mời thêm mỗi ngày"
          value={perDayNeeded != null ? formatNumber(perDayNeeded) : "—"}
          hint={daysLeft > 0 ? `${daysLeft} ngày tới hạn chót` : "đã tới hạn"}
        />
        <StatCard label="Thực tế tham dự" value={formatNumber(attendedTotal)} hint={`${formatNumber(decidedTotal)}/${formatNumber(invitedTotal)} khách đã chốt đi hay không`} />
        <StatCard
          label="Tham dự / đã mời"
          value={invitedTotal > 0 ? formatPercent((attendedTotal / invitedTotal) * 100) : "—"}
          hint="so sánh thực tế với lượng khách mời"
        />
      </div>

      {showTerritoryTable && (
        <div className="mt-6">
          <SectionTitle hint="Ban giám đốc giao">Chỉ tiêu theo khu vực</SectionTitle>
          {territoryQuotas.length === 0 ? (
            <EmptyState message="Chưa có chỉ tiêu khu vực nào." hint={canSetTerritoryQuota ? "Thêm ở form bên dưới." : undefined} />
          ) : (
            <TableWrap>
              <thead>
                <tr>
                  <th>Khu vực</th>
                  <th className="text-right">Chỉ tiêu</th>
                  <th className="text-right">Đã mời</th>
                  <th className="text-right">Tham dự</th>
                  <th style={{ width: 160 }}>Tiến độ</th>
                </tr>
              </thead>
              <tbody>
                {territoryQuotas.map((r) => (
                  <tr key={r.territoryId}>
                    <td className="font-medium text-ink-700">{r.territoryName}</td>
                    <td className="tnum text-right">
                      {canSetTerritoryQuota ? (
                        <QuotaInput action={setTerritoryQuotaAction} hidden={{ eventId: event.id, territoryId: r.territoryId }} defaultValue={r.quota} success="Đã lưu chỉ tiêu khu vực." />
                      ) : (
                        formatNumber(r.quota)
                      )}
                    </td>
                    <td className="tnum text-right font-medium">{formatNumber(r.invitedCount)}</td>
                    <td className="tnum text-right text-ink-500">{formatNumber(r.attendedCount)}</td>
                    <td>{r.quota > 0 && <ProgressBar percent={(r.invitedCount / r.quota) * 100} />}</td>
                  </tr>
                ))}
              </tbody>
            </TableWrap>
          )}
          {canSetTerritoryQuota && regionsWithoutQuota.length > 0 && (
            <ActionForm action={setTerritoryQuotaAction} success="Đã lưu chỉ tiêu khu vực." className="mt-2 flex flex-wrap items-end gap-2">
              <input type="hidden" name="eventId" value={event.id} />
              <div>
                <label className="label-caps mb-1 block text-[10px]">Thêm khu vực</label>
                <select name="territoryId" className="input py-1 text-sm">
                  {regionsWithoutQuota.map((r) => (
                    <option key={r.id} value={r.id}>
                      {r.name}
                    </option>
                  ))}
                </select>
              </div>
              <input name="quota" type="number" min={0} defaultValue={0} className="input w-20 py-1 text-sm" aria-label="Chỉ tiêu" />
              <button type="submit" className="btn-ghost px-2 py-1 text-xs">
                + Giao chỉ tiêu
              </button>
            </ActionForm>
          )}
        </div>
      )}

      {session.role !== "SALES" && (deptQuotas.length > 0 || assignableDepartments.length > 0) && (
        <div className="mt-6">
          <SectionTitle hint="GĐ khu vực / Ban giám đốc giao cho phòng ban, team">Chỉ tiêu theo phòng ban / team</SectionTitle>
          {deptQuotas.length === 0 ? (
            <EmptyState message="Chưa giao chỉ tiêu cho phòng ban / team nào." />
          ) : (
            <TableWrap>
              <thead>
                <tr>
                  <th>Phòng ban / Team</th>
                  <th className="text-right">Chỉ tiêu</th>
                  <th className="text-right">Đã chia cho NV</th>
                  <th className="text-right">Đã mời</th>
                  <th className="text-right">Tham dự</th>
                  <th style={{ width: 160 }}>Tiến độ</th>
                </tr>
              </thead>
              <tbody>
                {deptQuotas.map((r) => {
                  const diff = r.allocated - r.quota;
                  return (
                    <tr key={r.departmentId}>
                      <td className="font-medium text-ink-700">{r.departmentName}</td>
                      <td className="tnum text-right">
                        {canSetDeptQuotaIds.has(r.departmentId) ? (
                          <QuotaInput action={setDeptQuotaAction} hidden={{ eventId: event.id, departmentId: r.departmentId }} defaultValue={r.quota} success="Đã lưu chỉ tiêu phòng ban." />
                        ) : (
                          formatNumber(r.quota)
                        )}
                      </td>
                      <td className="tnum text-right">
                        {formatNumber(r.allocated)}
                        {r.quota > 0 && diff !== 0 && (
                          <div className="mt-0.5">
                            <Badge tone={diff > 0 ? "red" : "gold"}>{diff > 0 ? `vượt ${formatNumber(diff)}` : `chưa chia ${formatNumber(-diff)}`}</Badge>
                          </div>
                        )}
                      </td>
                      <td className="tnum text-right font-medium">{formatNumber(r.invitedCount)}</td>
                      <td className="tnum text-right text-ink-500">{formatNumber(r.attendedCount)}</td>
                      <td>{r.quota > 0 && <ProgressBar percent={(r.invitedCount / r.quota) * 100} />}</td>
                    </tr>
                  );
                })}
              </tbody>
            </TableWrap>
          )}
          {assignableDepartments.length > 0 && (
            <ActionForm action={setDeptQuotaAction} success="Đã lưu chỉ tiêu phòng ban." className="mt-2 flex flex-wrap items-end gap-2">
              <input type="hidden" name="eventId" value={event.id} />
              <div>
                <label className="label-caps mb-1 block text-[10px]">Thêm phòng ban / team</label>
                <select name="departmentId" className="input py-1 text-sm">
                  {assignableDepartments.map((d) => (
                    <option key={d.id} value={d.id}>
                      {d.name}
                    </option>
                  ))}
                </select>
              </div>
              <input name="quota" type="number" min={0} defaultValue={0} className="input w-20 py-1 text-sm" aria-label="Chỉ tiêu" />
              <button type="submit" className="btn-ghost px-2 py-1 text-xs">
                + Giao chỉ tiêu
              </button>
            </ActionForm>
          )}
        </div>
      )}

      {(session.role !== "SALES" || staffQuotas.length > 0) && (
        <div className="mt-6">
          <SectionTitle hint={session.role === "SALES" ? "chỉ tiêu quản lý giao cho bạn" : "Quản lý / GĐ khu vực giao cho nhân viên trong nhánh mình"}>Chỉ tiêu theo nhân viên</SectionTitle>
          {staffQuotas.length === 0 ? (
            <EmptyState message="Chưa giao chỉ tiêu cho nhân viên nào." />
          ) : (
            <TableWrap>
              <thead>
                <tr>
                  <th>Nhân viên</th>
                  <th>Khu vực</th>
                  <th className="text-right">Chỉ tiêu</th>
                  <th className="text-right">Đã mời</th>
                  <th className="text-right">Tham dự</th>
                  <th style={{ width: 160 }}>Tiến độ</th>
                </tr>
              </thead>
              <tbody>
                {staffQuotas.map((r) => (
                  <tr key={r.userId}>
                    <td className="font-medium text-ink-700">{r.userName}</td>
                    <td className="text-ink-500">{r.territoryName}</td>
                    <td className="tnum text-right">
                      {canSetStaffQuotaIds.has(r.userId) ? (
                        <QuotaInput action={setStaffQuotaAction} hidden={{ eventId: event.id, userId: r.userId }} defaultValue={r.quota} success="Đã lưu chỉ tiêu nhân viên." />
                      ) : (
                        formatNumber(r.quota)
                      )}
                    </td>
                    <td className="tnum text-right font-medium">{formatNumber(r.invitedCount)}</td>
                    <td className="tnum text-right text-ink-500">{formatNumber(r.attendedCount)}</td>
                    <td>{r.quota > 0 && <ProgressBar percent={(r.invitedCount / r.quota) * 100} />}</td>
                  </tr>
                ))}
              </tbody>
            </TableWrap>
          )}
          {assignableStaff.length > 0 && (
            <ActionForm action={setStaffQuotaAction} success="Đã lưu chỉ tiêu nhân viên." className="mt-2 flex flex-wrap items-end gap-2">
              <input type="hidden" name="eventId" value={event.id} />
              <div>
                <label className="label-caps mb-1 block text-[10px]">Thêm nhân viên</label>
                <select name="userId" className="input py-1 text-sm" defaultValue={assignableStaff[0]?.id}>
                  {assignableStaff.map((u) => (
                    <option key={u.id} value={u.id}>
                      {u.fullName} · {u.departmentName ?? "—"}
                    </option>
                  ))}
                </select>
              </div>
              <input name="quota" type="number" min={0} defaultValue={0} className="input w-20 py-1 text-sm" aria-label="Chỉ tiêu" />
              <button type="submit" className="btn-ghost px-2 py-1 text-xs">
                + Giao chỉ tiêu
              </button>
            </ActionForm>
          )}
        </div>
      )}

      {byType.length > 0 && (
        <div className="mt-6 grid gap-4 lg:grid-cols-2">
          <div>
            <SectionTitle hint="ví dụ 10 bác sĩ · 5 chủ spa · 5 chủ TMV">Khách mời theo loại</SectionTitle>
            <TableWrap>
              <thead>
                <tr>
                  <th>Loại khách</th>
                  <th className="text-right">Đã mời</th>
                  <th className="text-right">Có đi</th>
                  <th className="text-right">Tham dự / mời</th>
                </tr>
              </thead>
              <tbody>
                {byType.map((row) => (
                  <tr key={row.type}>
                    <td className="font-medium text-ink-700">{row.type}</td>
                    <td className="tnum text-right">{formatNumber(row.invited)}</td>
                    <td className="tnum text-right text-ink-500">{formatNumber(row.attended)}</td>
                    <td className="tnum text-right">{row.invited > 0 ? formatPercent((row.attended / row.invited) * 100) : "—"}</td>
                  </tr>
                ))}
              </tbody>
            </TableWrap>
          </div>
          <div>
            <SectionTitle hint="cộng dồn tới hạn chót">Số khách mời theo ngày</SectionTitle>
            <TableWrap>
              <thead>
                <tr>
                  <th>Ngày</th>
                  <th className="text-right">Mời trong ngày</th>
                  <th className="text-right">Cộng dồn</th>
                  <th style={{ width: 120 }}>Tiến độ</th>
                </tr>
              </thead>
              <tbody>
                {byDay.map((row) => (
                  <tr key={row.date}>
                    <td className="tnum text-ink-500">{formatDate(row.date)}</td>
                    <td className="tnum text-right">{formatNumber(row.count)}</td>
                    <td className="tnum text-right font-medium">{formatNumber(row.cumulative)}</td>
                    <td>{quotaTotal > 0 && <ProgressBar percent={(row.cumulative / quotaTotal) * 100} />}</td>
                  </tr>
                ))}
              </tbody>
            </TableWrap>
          </div>
        </div>
      )}

      <div className="mt-6">
        <SectionTitle hint={`${guests.length} khách đã ghi nhận`}>Khách đã mời</SectionTitle>
        {guestTerritoryOptions.length > 0 && (
          <div className="flex flex-col gap-3">
            <AddGuestBatchForm eventId={event.id} territories={guestTerritoryOptions} />
            <AddGuestForm eventId={event.id} territories={guestTerritoryOptions} />
          </div>
        )}
        <div className="mt-3">
          <GuestList eventId={event.id} guests={guests} currentUserId={session.userId} manageableInviters={manageableInviters} />
        </div>
        <p className="mt-2 text-xs text-ink-400">
          Đánh dấu CME/chứng nhận ngay khi khách yêu cầu — tra lại nhanh hơn nhiều so với lục file Excel,
          nhất là lúc cấp chứng nhận sau cả tháng. Sau sự kiện, cập nhật “Có đi / Không đi” để so sánh khách thực tế với khách đã mời.
        </p>
      </div>
    </>
  );
}
