import Link from "next/link";
import { and, asc, eq } from "drizzle-orm";
import { requireSession } from "@/lib/auth";
import { db } from "@/db";
import { customers, trainingCourses } from "@/db/schema";
import { canManageSettings, scopeFilter } from "@/lib/rbac";
import { loadHistoryByEntity } from "@/lib/audit-view";
import { chainOptions, loadProposals, parseProposalQuery, proposalCounts, PROPOSAL_PAGE_SIZE, type ProposalQuery } from "@/lib/proposals";
import { PROPOSAL_TYPES } from "@/lib/proposal-types";
import { formatNumber } from "@/lib/format";
import { PageHeader, SectionTitle, EmptyState } from "@/components/ui";
import { ProposalForm, ProposalList } from "./proposal-client";

export const dynamic = "force-dynamic";

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

  // Không chọn tab: có phiếu đang chờ tôi duyệt thì mở tab "Cần tôi duyệt", không thì hiện tất cả.
  if (params.xem === undefined) {
    const counts = await proposalCounts(session);
    if (counts.duyet > 0) query = { ...query, view: "duyet" };
  }

  const scope = await scopeFilter(session, { tenantId: customers.tenantId, ownerId: customers.ownerId, territoryId: customers.territoryId });
  const [list, options, courseRows, customerRows] = await Promise.all([
    loadProposals(session, query),
    chainOptions(session),
    db
      .select({ id: trainingCourses.id, name: trainingCourses.name })
      .from(trainingCourses)
      .where(and(eq(trainingCourses.tenantId, session.tenantId), eq(trainingCourses.isActive, true)))
      .orderBy(asc(trainingCourses.name)),
    db
      .select({ id: customers.id, code: customers.code, orgName: customers.orgName })
      .from(customers)
      .where(and(scope, eq(customers.isActive, true)))
      .orderBy(asc(customers.orgName))
      .limit(1000),
  ]);
  const { rows, total, page, totalPages, counts } = list;
  // Ban giám đốc (Admin) thấy lịch sử chỉnh sửa của từng phiếu và sửa/xoá được phiếu đã gửi.
  const isAdmin = canManageSettings(session);
  const history = isAdmin ? await loadHistoryByEntity(session.tenantId, rows.map((r) => r.id), ["proposal"]) : {};

  const href = (patch: Partial<ProposalQuery> = {}) => {
    const next = { ...query, page: 1, ...patch };
    const qs = new URLSearchParams();
    qs.set("xem", next.view || "tat-ca");
    if (next.status) qs.set("tt", next.status);
    if (next.type) qs.set("loai", next.type);
    if (next.q) qs.set("q", next.q);
    if (next.page > 1) qs.set("trang", String(next.page));
    return `/cong-viec/de-xuat?${qs.toString()}`;
  };
  const tabs = [
    { view: "duyet", label: "Cần tôi duyệt", count: counts.duyet },
    { view: "toi", label: "Tôi đề xuất", count: counts.toi },
    { view: "", label: session.role === "DIRECTOR" ? "Toàn công ty" : "Tất cả của tôi", count: counts.all },
  ] as const;

  return (
    <>
      <PageHeader
        title="Đề xuất"
        subtitle="Phiếu đề xuất mở lớp chuyển giao, khuyến mãi, quà tặng hoặc đề xuất khác. Duyệt lần lượt: Trưởng bộ phận → Trưởng bộ phận liên quan → TGĐ."
        actions={
          <Link href="/cong-viec" className="btn-ghost">
            ← Công việc
          </Link>
        }
      />

      <SectionTitle>Tạo phiếu đề xuất</SectionTitle>
      <div className="mb-6">
        <ProposalForm
          options={options}
          courses={courseRows}
          customers={customerRows.map((c) => ({ id: c.id, label: `${c.orgName} · ${c.code}` }))}
        />
      </div>

      <div className="mb-3 flex flex-wrap gap-1.5">
        {tabs.map((tab) => (
          <Link
            key={tab.label}
            href={href({ view: tab.view })}
            className={`rounded-full border px-3 py-1 text-sm font-semibold ${
              query.view === tab.view
                ? "border-brand-500 bg-brand-500 text-white"
                : tab.view === "duyet" && tab.count > 0
                  ? "border-gold-500 bg-gold-100 text-ink-700"
                  : "border-[var(--color-line)] bg-white text-ink-500 hover:bg-ink-50"
            }`}
          >
            {tab.label} <span className="tnum font-normal opacity-80">{formatNumber(tab.count)}</span>
          </Link>
        ))}
      </div>

      <form className="mb-4 flex flex-wrap items-end gap-3" action="/cong-viec/de-xuat">
        <input type="hidden" name="xem" value={query.view || "tat-ca"} />
        <div className="min-w-48 flex-1">
          <label htmlFor="q" className="label-caps mb-1.5 block">
            Tìm phiếu
          </label>
          <input id="q" name="q" defaultValue={query.q} className="input" placeholder="Tiêu đề hoặc nội dung…" />
        </div>
        <div>
          <label htmlFor="loai" className="label-caps mb-1.5 block">
            Loại phiếu
          </label>
          <select id="loai" name="loai" defaultValue={query.type} className="input">
            <option value="">Tất cả</option>
            {PROPOSAL_TYPES.map((t) => (
              <option key={t.key} value={t.key}>
                {t.label}
              </option>
            ))}
          </select>
        </div>
        <div>
          <label htmlFor="tt" className="label-caps mb-1.5 block">
            Trạng thái
          </label>
          <select id="tt" name="tt" defaultValue={query.status} className="input">
            <option value="">Tất cả</option>
            <option value="PENDING">Chờ duyệt</option>
            <option value="APPROVED">Đã duyệt</option>
            <option value="REJECTED">Từ chối</option>
          </select>
        </div>
        <button type="submit" className="btn-ghost">
          Lọc
        </button>
      </form>

      <SectionTitle hint={`${formatNumber(total)} phiếu`}>Phiếu đề xuất</SectionTitle>
      {rows.length === 0 ? (
        <EmptyState
          message="Không có phiếu đề xuất nào."
          hint={query.view === "duyet" ? "Hiện không có phiếu nào đang chờ đến lượt bạn duyệt." : "Tạo phiếu mới ở khung phía trên."}
        />
      ) : (
        <ProposalList
          proposals={rows}
          currentUserId={session.userId}
          admin={isAdmin ? { courses: courseRows, customers: customerRows.map((c) => ({ id: c.id, label: `${c.orgName} · ${c.code}` })), history } : undefined}
        />
      )}

      {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) * PROPOSAL_PAGE_SIZE + 1}–{Math.min(page * PROPOSAL_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>
      )}
    </>
  );
}
