import { redirect } from "next/navigation";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { isAdminEmail, listAdminEmails } from "@/lib/admin";
import { payoutRepo } from "@/server/repositories/payout.repo";
import { AdminFilterBar } from "@/features/admin/components/admin-filter-bar";
import { ExportCsvLink } from "@/features/admin/components/export-csv-link";
import {
  PayoutReviewCard,
  type PayoutCardData,
} from "@/features/payout/components/payout-review-card";

type Tab = "RELEASED" | "HELD" | "PAID" | "CANCELLED";

const TABS: { key: Tab; label: string }[] = [
  { key: "RELEASED", label: "Siap transfer" },
  { key: "HELD", label: "Ditahan (escrow)" },
  { key: "PAID", label: "Selesai" },
  { key: "CANCELLED", label: "Dibatalkan" },
];

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 AdminPayoutsPage({ searchParams }: PageProps) {
  const session = await getServerSession(authOptions);
  if (!session?.user) redirect("/login?callbackUrl=/admin/payouts");
  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 = TABS.some((t) => t.key === params.tab)
    ? (params.tab as Tab)
    : "RELEASED";

  const rows = await payoutRepo.listByStatus(tab, {
    dateFrom: parseDate(params.dateFrom),
    dateTo: parseDate(params.dateTo),
    processorEmail: params.reviewer || undefined,
  });
  const items: PayoutCardData[] = rows.map((p) => ({
    id: p.id,
    amount: p.amount,
    currency: p.currency,
    status: p.status,
    heldUntil: p.heldUntil,
    releasedAt: p.releasedAt,
    paidAt: p.paidAt,
    cancelledAt: p.cancelledAt,
    bankName: p.bankName,
    bankAccountNumber: p.bankAccountNumber,
    bankAccountName: p.bankAccountName,
    adminNote: p.adminNote,
    createdAt: p.createdAt,
    trip: p.trip,
    organizer: p.organizer,
    booking: {
      id: p.booking.id,
      amount: p.booking.amount,
      status: p.booking.status,
      user: p.booking.user,
    },
    processedBy: p.processedBy,
  }));

  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">
            Payout Organizer
          </h1>
          <p className="mt-1 text-sm text-neutral-500">
            Uang peserta ditahan (escrow) sampai trip selesai + 3 hari. Setelah
            status <strong>Siap transfer</strong>, admin transfer manual ke
            rekening organizer lalu tandai sudah dibayar.
          </p>
        </div>
        <ExportCsvLink
          href="/api/admin/export/payouts"
          query={exportQuery.toString()}
        />
      </header>

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

      <div className="mb-6 flex flex-wrap gap-2">
        {TABS.map((t) => (
          <a
            key={t.key}
            href={`/admin/payouts?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 payout yang cocok dengan filter ini.
          </p>
        </div>
      ) : (
        <div className="space-y-4">
          {items.map((p) => (
            <PayoutReviewCard key={p.id} payout={p} />
          ))}
        </div>
      )}
    </div>
  );
}
