import { redirect } from "next/navigation";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { isAdminEmail, listAdminEmails } from "@/lib/admin";
import { organizerRepo } from "@/server/repositories/organizer.repo";
import { organizerService } from "@/server/services/organizer.service";
import { AdminFilterBar } from "@/features/admin/components/admin-filter-bar";
import { ExportCsvLink } from "@/features/admin/components/export-csv-link";
import { ReviewCard } from "@/features/organizer/components/review-card";

type Tab = "PENDING" | "APPROVED" | "REJECTED";

interface PageProps {
  searchParams: Promise<{
    tab?: string;
    dateFrom?: string;
    dateTo?: string;
    reviewer?: string;
  }>;
}

function parseDate(value: string | undefined): Date | undefined {
  if (!value) return undefined;
  const d = new Date(value);
  return Number.isNaN(d.getTime()) ? undefined : d;
}

export default async function AdminVerificationsPage({ searchParams }: PageProps) {
  const session = await getServerSession(authOptions);
  if (!session?.user) redirect("/login?callbackUrl=/admin/verifications");
  if (!isAdminEmail(session.user.email)) {
    return (
      <div className="mx-auto max-w-2xl px-4 py-12 text-center">
        <p className="text-sm text-neutral-600">
          Halaman ini hanya untuk admin SeTrip.
        </p>
      </div>
    );
  }

  const params = await searchParams;
  const tab: Tab =
    params.tab === "APPROVED" || params.tab === "REJECTED" ? params.tab : "PENDING";

  const rows = await organizerRepo.listByStatus(tab, {
    dateFrom: parseDate(params.dateFrom),
    dateTo: parseDate(params.dateTo),
    reviewerEmail: params.reviewer || undefined,
  });
  const items = rows.map((v) => ({
    id: v.id,
    fullName: v.fullName,
    nik: organizerService.decryptNik(v.nikEncrypted),
    birthDate: v.birthDate,
    address: v.address,
    bankName: v.bankName,
    bankAccountNumber: v.bankAccountNumber,
    bankAccountName: v.bankAccountName,
    status: v.status,
    rejectionReason: v.rejectionReason,
    reviewedAt: v.reviewedAt,
    createdAt: v.createdAt,
    user: v.user,
    reviewedBy: v.reviewedBy,
  }));

  const tabs: { key: Tab; label: string }[] = [
    { key: "PENDING", label: "Pending" },
    { key: "APPROVED", label: "Disetujui" },
    { key: "REJECTED", label: "Ditolak" },
  ];

  const exportQuery = new URLSearchParams({ status: tab });
  if (params.dateFrom) exportQuery.set("dateFrom", params.dateFrom);
  if (params.dateTo) exportQuery.set("dateTo", params.dateTo);
  if (params.reviewer) exportQuery.set("reviewer", params.reviewer);

  return (
    <div className="mx-auto max-w-4xl px-4 py-8 sm:py-12">
      <header className="mb-6 flex flex-wrap items-start justify-between gap-3">
        <div>
          <h1 className="text-2xl font-bold text-neutral-900 sm:text-3xl">
            Review Verifikasi Organizer
          </h1>
          <p className="mt-1 text-sm text-neutral-500">
            Periksa data KTP, foto liveness (memegang kertas SETRIP), dan rekening
            sebelum menyetujui.
          </p>
        </div>
        <ExportCsvLink
          href="/api/admin/export/verifications"
          query={exportQuery.toString()}
        />
      </header>

      <AdminFilterBar
        action="/admin/verifications"
        values={{
          tab,
          dateFrom: params.dateFrom,
          dateTo: params.dateTo,
          reviewer: params.reviewer,
        }}
        reviewerOptions={listAdminEmails()}
        reviewerLabel="Reviewer"
      />

      <div className="mb-6 flex gap-2">
        {tabs.map((t) => (
          <a
            key={t.key}
            href={`/admin/verifications?tab=${t.key}`}
            className={`rounded-full px-4 py-1.5 text-sm font-semibold transition-colors ${
              tab === t.key
                ? "bg-primary-600 text-white"
                : "bg-neutral-100 text-neutral-600 hover:bg-neutral-200"
            }`}
          >
            {t.label}
          </a>
        ))}
      </div>

      {items.length === 0 ? (
        <div className="rounded-2xl border border-dashed border-neutral-300 bg-white p-10 text-center">
          <p className="text-sm text-neutral-500">
            Tidak ada data yang cocok dengan filter ini.
          </p>
        </div>
      ) : (
        <div className="space-y-4">
          {items.map((v) => (
            <ReviewCard key={v.id} verification={v} />
          ))}
        </div>
      )}
    </div>
  );
}
