import { redirect } from "next/navigation";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { isAdminEmail, listAdminEmails } from "@/lib/admin";
import { refundRepo } from "@/server/repositories/refund.repo";
import { CreateRefundForm } from "@/features/refund/components/create-refund-form";
import { AdminFilterBar } from "@/features/admin/components/admin-filter-bar";
import { ExportCsvLink } from "@/features/admin/components/export-csv-link";
import {
  RefundReviewCard,
  type RefundCardData,
} from "@/features/refund/components/refund-review-card";

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

const TABS: { key: Tab; label: string }[] = [
  { key: "PENDING", label: "Pending" },
  { key: "APPROVED", label: "Disetujui" },
  { key: "SUCCEEDED", label: "Selesai" },
  { key: "REJECTED", label: "Ditolak" },
  { key: "FAILED", label: "Gagal" },
];

const REASON_OPTIONS = [
  { value: "USER_CANCELLATION", label: "User cancel" },
  { value: "ORGANIZER_CANCELLED", label: "Organizer cancel" },
  { value: "TRIP_ISSUE", label: "Trip issue" },
  { value: "ADMIN_ADJUSTMENT", label: "Admin adjustment" },
  { value: "DISPUTE_RESOLVED", label: "Dispute resolved" },
] as const;

type ReasonValue = (typeof REASON_OPTIONS)[number]["value"];

interface PageProps {
  searchParams: Promise<{
    tab?: string;
    dateFrom?: string;
    dateTo?: string;
    reviewer?: string;
    reason?: 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 AdminRefundsPage({ searchParams }: PageProps) {
  const session = await getServerSession(authOptions);
  if (!session?.user) redirect("/login?callbackUrl=/admin/refunds");
  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)
    : "PENDING";
  const reason: ReasonValue | undefined = REASON_OPTIONS.some(
    (r) => r.value === params.reason
  )
    ? (params.reason as ReasonValue)
    : undefined;

  const rows = await refundRepo.listByStatus(tab, {
    dateFrom: parseDate(params.dateFrom),
    dateTo: parseDate(params.dateTo),
    reviewerEmail: params.reviewer || undefined,
    reason,
  });

  const items: RefundCardData[] = rows.map((r) => ({
    id: r.id,
    amount: r.amount,
    currency: r.currency,
    reason: r.reason,
    reportedBy: r.reportedBy,
    reportNote: r.reportNote,
    initiatedBy: r.initiatedBy,
    status: r.status,
    adminNote: r.adminNote,
    createdAt: r.createdAt,
    reviewedAt: r.reviewedAt,
    succeededAt: r.succeededAt,
    failedAt: r.failedAt,
    reviewedBy: r.reviewedBy,
    booking: {
      id: r.booking.id,
      amount: r.booking.amount,
      status: r.booking.status,
      trip: {
        id: r.booking.trip.id,
        title: r.booking.trip.title,
        date: r.booking.trip.date,
      },
      user: r.booking.user,
      payments: r.booking.payments.map((p) => ({
        id: p.id,
        provider: p.provider,
        method: p.method,
        amount: p.amount,
        status: p.status,
        paidAt: p.paidAt,
      })),
    },
  }));

  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);
  if (reason) exportQuery.set("reason", reason);

  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 Refund Manual
          </h1>
          <p className="mt-1 text-sm text-neutral-500">
            Tinjau laporan refund dari peserta dan organizer. Setiap refund harus
            melalui approval admin sebelum dieksekusi.
          </p>
        </div>
        <ExportCsvLink
          href="/api/admin/export/refunds"
          query={exportQuery.toString()}
        />
      </header>

      <CreateRefundForm />

      <AdminFilterBar
        action="/admin/refunds"
        values={{
          tab,
          dateFrom: params.dateFrom,
          dateTo: params.dateTo,
          reviewer: params.reviewer,
          reason: params.reason,
        }}
        reviewerOptions={listAdminEmails()}
        reviewerLabel="Reviewer"
        reasonOptions={[...REASON_OPTIONS]}
      />

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