import { redirect } from "next/navigation";
import Link from "next/link";
import { getServerSession } from "next-auth";
import { ChevronRight } from "lucide-react";
import { authOptions } from "@/lib/auth";
import { organizerRepo } from "@/server/repositories/organizer.repo";
import { refundRepo } from "@/server/repositories/refund.repo";
import { payoutRepo } from "@/server/repositories/payout.repo";

const REFUND_REASON_LABEL: Record<string, string> = {
  USER_CANCELLATION: "Peserta cancel",
  ORGANIZER_CANCELLED: "Organizer cancel",
  TRIP_ISSUE: "Masalah trip",
  ADMIN_ADJUSTMENT: "Penyesuaian admin",
  DISPUTE_RESOLVED: "Dispute selesai",
  OTHER: "Lainnya",
};

function formatIDR(n: number) {
  return `Rp${n.toLocaleString("id-ID")}`;
}

function timeAgo(d: Date) {
  const diff = Date.now() - new Date(d).getTime();
  const h = Math.floor(diff / 3600000);
  if (h < 1) return `${Math.max(1, Math.floor(diff / 60000))} mnt lalu`;
  if (h < 24) return `${h} jam lalu`;
  const days = Math.floor(h / 24);
  return `${days} hari lalu`;
}

export default async function AdminDashboardPage() {
  const session = await getServerSession(authOptions);
  if (!session?.user) redirect("/login?callbackUrl=/admin");
  if (!session.user.isAdmin) {
    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 [
    pendingVerif,
    approvedVerif,
    rejectedVerif,
    pendingRefund,
    approvedRefund,
    succeededRefund,
    heldPayout,
    releasedPayout,
    paidPayout,
    recentPendingVerif,
    recentPendingRefund,
    recentApprovedRefund,
    recentReleasedPayout,
  ] = await Promise.all([
    organizerRepo.countByStatus("PENDING"),
    organizerRepo.countByStatus("APPROVED"),
    organizerRepo.countByStatus("REJECTED"),
    refundRepo.countByStatus("PENDING"),
    refundRepo.countByStatus("APPROVED"),
    refundRepo.countByStatus("SUCCEEDED"),
    payoutRepo.countByStatus("HELD"),
    payoutRepo.countByStatus("RELEASED"),
    payoutRepo.countByStatus("PAID"),
    organizerRepo.listRecent("PENDING", 3),
    refundRepo.listRecent("PENDING", 3),
    refundRepo.listRecent("APPROVED", 3),
    payoutRepo.listRecent("RELEASED", 3),
  ]);

  const stats: Array<{
    label: string;
    value: number;
    hint: string;
    href: string;
    accent: "amber" | "blue" | "primary";
  }> = [
    {
      label: "Verifikasi menunggu",
      value: pendingVerif,
      hint: "KYC organizer perlu ditinjau",
      href: "/admin/verifications?tab=PENDING",
      accent: "amber",
    },
    {
      label: "Refund baru",
      value: pendingRefund,
      hint: "Perlu disetujui / ditolak",
      href: "/admin/refunds?tab=PENDING",
      accent: "amber",
    },
    {
      label: "Refund siap transfer",
      value: approvedRefund,
      hint: "Refund APPROVED — transfer ke peserta lalu mark SUCCEEDED",
      href: "/admin/refunds?tab=APPROVED",
      accent: "blue",
    },
    {
      label: "Payout siap transfer",
      value: releasedPayout,
      hint: "Escrow lepas — transfer ke organizer",
      href: "/admin/payouts?tab=RELEASED",
      accent: "blue",
    },
  ];

  const accentClasses: Record<typeof stats[number]["accent"], string> = {
    amber: "bg-amber-50 text-amber-900 ring-amber-200",
    blue: "bg-blue-50 text-blue-900 ring-blue-200",
    primary: "bg-primary-50 text-primary-900 ring-primary-200",
  };

  const totalAttention =
    pendingVerif + pendingRefund + approvedRefund + releasedPayout;

  return (
    <div className="mx-auto max-w-5xl px-4 py-8 sm:py-12">
      <header className="mb-8">
        <p className="text-xs font-semibold uppercase tracking-wide text-primary-600">
          Admin
        </p>
        <h1 className="mt-1 text-2xl font-bold text-neutral-900 sm:text-3xl">
          Dashboard
        </h1>
        <p className="mt-1 text-sm text-neutral-500">
          Halo {session.user.name}.{" "}
          {totalAttention > 0 ? (
            <>
              Ada <strong className="text-neutral-800">{totalAttention}</strong>{" "}
              hal yang menunggu tindakan kamu.
            </>
          ) : (
            <>Tidak ada antrian pending — semua sudah beres ✨</>
          )}
        </p>
      </header>

      {/* Stats row */}
      <section className="mb-8 grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
        {stats.map((s) => (
          <Link
            key={s.label}
            href={s.href}
            className={`group rounded-2xl bg-white p-5 ring-1 transition-shadow hover:shadow-md ${
              s.value > 0 ? "ring-neutral-200" : "ring-neutral-100"
            }`}
          >
            <div className="flex items-center justify-between">
              <span
                className={`inline-flex rounded-full px-2.5 py-0.5 text-[11px] font-semibold ring-1 ${accentClasses[s.accent]}`}
              >
                {s.label}
              </span>
              <span className="inline-flex items-center gap-1 text-xs text-neutral-400 group-hover:text-primary-600">
                Buka
                <ChevronRight size={14} strokeWidth={2} aria-hidden />
              </span>
            </div>
            <p className="mt-3 text-3xl font-bold text-neutral-900">{s.value}</p>
            <p className="mt-1 text-xs text-neutral-500">{s.hint}</p>
          </Link>
        ))}
      </section>

      {/* Pending Verifikasi */}
      <section className="mb-8 rounded-2xl border border-neutral-200 bg-white">
        <div className="flex items-center justify-between border-b border-neutral-100 px-5 py-4">
          <div>
            <h2 className="text-base font-bold text-neutral-800">
              Verifikasi Organizer
            </h2>
            <p className="text-xs text-neutral-500">
              {approvedVerif} disetujui · {rejectedVerif} ditolak ·{" "}
              {pendingVerif} menunggu
            </p>
          </div>
          <Link
            href="/admin/verifications?tab=PENDING"
            className="rounded-lg bg-primary-600 px-3 py-1.5 text-xs font-semibold text-white hover:bg-primary-700"
          >
            Tinjau pending ({pendingVerif})
          </Link>
        </div>
        {recentPendingVerif.length === 0 ? (
          <p className="px-5 py-6 text-sm text-neutral-500">
            Tidak ada pengajuan menunggu review.
          </p>
        ) : (
          <ul className="divide-y divide-neutral-100">
            {recentPendingVerif.map((v) => (
              <li
                key={v.id}
                className="flex items-center justify-between gap-3 px-5 py-3"
              >
                <div className="min-w-0 flex-1">
                  <p className="truncate text-sm font-semibold text-neutral-800">
                    {v.fullName}
                  </p>
                  <p className="truncate text-xs text-neutral-500">
                    {v.user.name} · {v.user.email} · {timeAgo(v.createdAt)}
                  </p>
                </div>
                <Link
                  href="/admin/verifications?tab=PENDING"
                  className="shrink-0 rounded-lg border border-neutral-200 px-3 py-1.5 text-xs font-medium text-neutral-700 hover:bg-neutral-50"
                >
                  Buka
                </Link>
              </li>
            ))}
          </ul>
        )}
      </section>

      {/* Refund — Pending & Siap Transfer */}
      <section className="mb-8 rounded-2xl border border-neutral-200 bg-white">
        <div className="flex items-center justify-between border-b border-neutral-100 px-5 py-4">
          <div>
            <h2 className="text-base font-bold text-neutral-800">Refund</h2>
            <p className="text-xs text-neutral-500">
              {succeededRefund} selesai · {approvedRefund} siap transfer ·{" "}
              {pendingRefund} baru
            </p>
          </div>
          <Link
            href="/admin/refunds?tab=PENDING"
            className="rounded-lg bg-primary-600 px-3 py-1.5 text-xs font-semibold text-white hover:bg-primary-700"
          >
            Tinjau refund
          </Link>
        </div>

        <div className="grid divide-neutral-100 sm:grid-cols-2 sm:divide-x">
          <div className="px-5 py-4">
            <p className="mb-2 text-xs font-semibold uppercase tracking-wide text-amber-700">
              Pending ({pendingRefund})
            </p>
            {recentPendingRefund.length === 0 ? (
              <p className="text-sm text-neutral-500">
                Tidak ada refund baru.
              </p>
            ) : (
              <ul className="space-y-2">
                {recentPendingRefund.map((r) => (
                  <li key={r.id} className="text-sm">
                    <Link
                      href="/admin/refunds?tab=PENDING"
                      className="block rounded-lg p-2 -m-2 hover:bg-neutral-50"
                    >
                      <p className="font-semibold text-neutral-800">
                        {formatIDR(r.amount)} ·{" "}
                        <span className="font-normal text-neutral-500">
                          {REFUND_REASON_LABEL[r.reason] ?? r.reason}
                        </span>
                      </p>
                      <p className="truncate text-xs text-neutral-500">
                        {r.booking.user.name} · {r.booking.trip.title} ·{" "}
                        {timeAgo(r.createdAt)}
                      </p>
                    </Link>
                  </li>
                ))}
              </ul>
            )}
          </div>

          <div className="px-5 py-4">
            <p className="mb-2 text-xs font-semibold uppercase tracking-wide text-blue-700">
              Siap transfer ({approvedRefund})
            </p>
            {recentApprovedRefund.length === 0 ? (
              <p className="text-sm text-neutral-500">
                Tidak ada refund siap transfer.
              </p>
            ) : (
              <ul className="space-y-2">
                {recentApprovedRefund.map((r) => (
                  <li key={r.id} className="text-sm">
                    <Link
                      href="/admin/refunds?tab=APPROVED"
                      className="block rounded-lg p-2 -m-2 hover:bg-neutral-50"
                    >
                      <p className="font-semibold text-neutral-800">
                        {formatIDR(r.amount)} ·{" "}
                        <span className="font-normal text-neutral-500">
                          {REFUND_REASON_LABEL[r.reason] ?? r.reason}
                        </span>
                      </p>
                      <p className="truncate text-xs text-neutral-500">
                        {r.booking.user.name} · {r.booking.trip.title} ·{" "}
                        {timeAgo(r.createdAt)}
                      </p>
                    </Link>
                  </li>
                ))}
              </ul>
            )}
          </div>
        </div>
      </section>

      {/* Payout — escrow ke organizer */}
      <section className="mb-8 rounded-2xl border border-neutral-200 bg-white">
        <div className="flex items-center justify-between border-b border-neutral-100 px-5 py-4">
          <div>
            <h2 className="text-base font-bold text-neutral-800">
              Payout Organizer (Escrow)
            </h2>
            <p className="text-xs text-neutral-500">
              {paidPayout} dibayar · {releasedPayout} siap transfer ·{" "}
              {heldPayout} ditahan
            </p>
          </div>
          <Link
            href="/admin/payouts?tab=RELEASED"
            className="rounded-lg bg-primary-600 px-3 py-1.5 text-xs font-semibold text-white hover:bg-primary-700"
          >
            Transfer payout ({releasedPayout})
          </Link>
        </div>
        {recentReleasedPayout.length === 0 ? (
          <p className="px-5 py-6 text-sm text-neutral-500">
            Tidak ada payout siap transfer.
          </p>
        ) : (
          <ul className="divide-y divide-neutral-100">
            {recentReleasedPayout.map((p) => (
              <li
                key={p.id}
                className="flex items-center justify-between gap-3 px-5 py-3"
              >
                <div className="min-w-0 flex-1">
                  <p className="truncate text-sm font-semibold text-neutral-800">
                    {formatIDR(p.amount)} · {p.organizer.name}
                  </p>
                  <p className="truncate text-xs text-neutral-500">
                    {p.trip.title} ·{" "}
                    {p.releasedAt
                      ? `release ${timeAgo(p.releasedAt)}`
                      : `hold sampai ${new Date(p.heldUntil).toLocaleDateString("id-ID")}`}
                  </p>
                </div>
                <Link
                  href="/admin/payouts?tab=RELEASED"
                  className="shrink-0 rounded-lg border border-neutral-200 px-3 py-1.5 text-xs font-medium text-neutral-700 hover:bg-neutral-50"
                >
                  Buka
                </Link>
              </li>
            ))}
          </ul>
        )}
      </section>

      <section className="rounded-2xl border border-dashed border-neutral-300 bg-neutral-50 px-5 py-4 text-xs text-neutral-500">
        <p className="mb-1">
          <span className="font-semibold">Refund APPROVED:</span> admin transfer
          manual ke peserta lalu tandai <span className="font-semibold">SUCCEEDED</span>.
        </p>
        <p>
          <span className="font-semibold">Payout RELEASED:</span> escrow dilepas
          karena trip sudah selesai + 3 hari. Admin transfer ke organizer lalu
          tandai <span className="font-semibold">PAID</span>.
        </p>
      </section>
    </div>
  );
}
