import Link from "next/link";
import { formatRupiah } from "@/lib/utils";

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

interface EarningRow {
  id: string;
  amount: number;
  status: PayoutStatus;
  heldUntil: Date;
  releasedAt: Date | null;
  paidAt: Date | null;
  cancelledAt: Date | null;
  trip: { id: string; title: string; date: Date; endDate: Date | null };
  booking: {
    id: string;
    amount: number;
    user: { id: string; name: string };
  };
}

interface EarningsSectionProps {
  payouts: EarningRow[];
}

function formatDay(d: Date | null | string): string {
  if (!d) return "—";
  return new Date(d).toLocaleDateString("id-ID", {
    day: "2-digit",
    month: "short",
    year: "numeric",
  });
}

const STATUS_META: Record<
  PayoutStatus,
  { label: string; cls: string; hint: (row: EarningRow) => string }
> = {
  HELD: {
    label: "Ditahan",
    cls: "bg-amber-50 text-amber-700 ring-amber-200",
    hint: (r) => `Cair setelah ${formatDay(r.heldUntil)}`,
  },
  RELEASED: {
    label: "Siap transfer",
    cls: "bg-blue-50 text-blue-700 ring-blue-200",
    hint: (r) =>
      r.releasedAt
        ? `Antri admin transfer sejak ${formatDay(r.releasedAt)}`
        : "Antri admin transfer",
  },
  PAID: {
    label: "Diterima",
    cls: "bg-primary-50 text-primary-700 ring-primary-200",
    hint: (r) =>
      r.paidAt ? `Ditransfer ${formatDay(r.paidAt)}` : "Sudah ditransfer admin",
  },
  CANCELLED: {
    label: "Dibatalkan",
    cls: "bg-neutral-100 text-neutral-600 ring-neutral-200",
    hint: () => "Trip dibatalkan / di-refund — tidak ada payout",
  },
};

export function EarningsSection({ payouts }: EarningsSectionProps) {
  if (payouts.length === 0) return null;

  const totals = {
    held: 0,
    released: 0,
    paid: 0,
  };
  for (const p of payouts) {
    if (p.status === "HELD") totals.held += p.amount;
    else if (p.status === "RELEASED") totals.released += p.amount;
    else if (p.status === "PAID") totals.paid += p.amount;
  }

  return (
    <section className="mb-8 rounded-2xl border border-neutral-200 bg-white p-5 shadow-sm sm:p-6">
      <header className="mb-4">
        <h2 className="text-base font-bold text-neutral-800 sm:text-lg">
          Pendapatan dari peserta
        </h2>
        <p className="mt-0.5 text-xs text-neutral-500">
          Uang peserta ditahan oleh SeTrip (escrow) sampai trip selesai + 3 hari,
          lalu admin transfer ke rekening bank yang kamu daftarkan.
        </p>
      </header>

      <div className="mb-5 grid grid-cols-3 gap-2 text-xs sm:text-sm">
        <Stat label="Ditahan" value={totals.held} accent="amber" />
        <Stat label="Siap transfer" value={totals.released} accent="blue" />
        <Stat label="Sudah diterima" value={totals.paid} accent="primary" />
      </div>

      <ul className="divide-y divide-neutral-100">
        {payouts.map((p) => {
          const meta = STATUS_META[p.status];
          return (
            <li
              key={p.id}
              className="flex flex-wrap items-start justify-between gap-3 py-3"
            >
              <div className="min-w-0 flex-1">
                <Link
                  href={`/trips/${p.trip.id}`}
                  className="block truncate text-sm font-semibold text-neutral-800 hover:text-primary-700"
                >
                  {p.trip.title}
                </Link>
                <p className="truncate text-xs text-neutral-500">
                  {p.booking.user.name} · trip {formatDay(p.trip.date)}
                </p>
                <p className="mt-1 text-[11px] text-neutral-500">
                  {meta.hint(p)}
                </p>
              </div>
              <div className="flex shrink-0 flex-col items-end gap-1">
                <span className="text-sm font-bold text-neutral-900">
                  {formatRupiah(p.amount)}
                </span>
                <span
                  className={`inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-semibold ring-1 ${meta.cls}`}
                >
                  {meta.label}
                </span>
              </div>
            </li>
          );
        })}
      </ul>
    </section>
  );
}

function Stat({
  label,
  value,
  accent,
}: {
  label: string;
  value: number;
  accent: "amber" | "blue" | "primary";
}) {
  const cls = {
    amber: "bg-amber-50 text-amber-900",
    blue: "bg-blue-50 text-blue-900",
    primary: "bg-primary-50 text-primary-900",
  }[accent];
  return (
    <div className={`rounded-xl px-3 py-2 ${cls}`}>
      <p className="text-[10px] font-semibold uppercase tracking-wide opacity-70">
        {label}
      </p>
      <p className="mt-0.5 text-sm font-bold sm:text-base">
        {formatRupiah(value)}
      </p>
    </div>
  );
}
