import { redirect } from "next/navigation";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { isAdminEmail } from "@/lib/admin";
import { payoutRepo } from "@/server/repositories/payout.repo";
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 }>;
}

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);
  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,
  }));

  return (
    <div className="mx-auto max-w-4xl px-4 py-8 sm:py-12">
      <header className="mb-6">
        <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>
      </header>

      <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 pada status ini.</p>
        </div>
      ) : (
        <div className="space-y-4">
          {items.map((p) => (
            <PayoutReviewCard key={p.id} payout={p} />
          ))}
        </div>
      )}
    </div>
  );
}
