import Link from "next/link";
import { redirect } from "next/navigation";
import { getServerSession } from "next-auth";
import { CalendarDays, MapPin } from "lucide-react";
import { authOptions } from "@/lib/auth";
import { isAdminEmail } from "@/lib/admin";
import { tripRepo } from "@/server/repositories/trip.repo";
import { formatRupiah } from "@/lib/utils";
import { formatTripCalendarDateRangeLong } from "@/lib/trip-dates";
import { categoryMeta } from "@/lib/activity-category";

type Tab = "ALL" | "OPEN" | "FULL" | "CLOSED" | "COMPLETED";

const TABS: { key: Tab; label: string }[] = [
  { key: "ALL", label: "Semua" },
  { key: "OPEN", label: "Open" },
  { key: "FULL", label: "Penuh" },
  { key: "CLOSED", label: "Dibatalkan" },
  { key: "COMPLETED", label: "Selesai" },
];

interface PageProps {
  searchParams: Promise<{ tab?: string; q?: string }>;
}

export default async function AdminTripsPage({ searchParams }: PageProps) {
  const session = await getServerSession(authOptions);
  if (!session?.user) redirect("/login?callbackUrl=/admin/trips");
  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)
    : "ALL";
  const q = (params.q ?? "").trim();

  const trips = await tripRepo.searchForAdmin({
    status: tab === "ALL" ? undefined : tab,
    q: q || undefined,
  });

  return (
    <div className="mx-auto max-w-5xl px-4 py-8 sm:py-12">
      <header className="mb-6">
        <h1 className="text-2xl font-bold text-neutral-900 sm:text-3xl">
          Trip Operations
        </h1>
        <p className="mt-1 text-sm text-neutral-500">
          Cari trip, lihat detail, dan intervensi (cancel + auto-refund) saat
          organizer unreachable.
        </p>
      </header>

      <form method="get" className="mb-4 flex gap-2">
        <input type="hidden" name="tab" value={tab} />
        <input
          name="q"
          defaultValue={q}
          placeholder="Cari judul, destinasi, lokasi, organizer..."
          className="flex-1 rounded-xl border border-neutral-200 bg-white px-4 py-2 text-sm text-neutral-800 placeholder:text-neutral-400 focus:border-primary-400"
        />
        <button
          type="submit"
          className="rounded-xl bg-primary-600 px-4 py-2 text-sm font-semibold text-white hover:bg-primary-700"
        >
          Cari
        </button>
        {q && (
          <Link
            href={`/admin/trips?tab=${tab}`}
            className="rounded-xl border border-neutral-200 bg-white px-4 py-2 text-sm font-semibold text-neutral-600 hover:bg-neutral-50"
          >
            Reset
          </Link>
        )}
      </form>

      <div className="mb-6 flex flex-wrap gap-2">
        {TABS.map((t) => (
          <Link
            key={t.key}
            href={`/admin/trips?tab=${t.key}${q ? `&q=${encodeURIComponent(q)}` : ""}`}
            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}
          </Link>
        ))}
      </div>

      {trips.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">
            {q
              ? `Tidak ada trip yang cocok dengan "${q}".`
              : "Tidak ada trip pada status ini."}
          </p>
        </div>
      ) : (
        <ul className="space-y-3">
          {trips.map((t) => {
            const cat = categoryMeta(t.category);
            return (
              <li
                key={t.id}
                className="rounded-2xl border border-neutral-200 bg-white p-4 shadow-sm transition-shadow hover:shadow-md sm:p-5"
              >
                <Link href={`/admin/trips/${t.id}`} className="block">
                  <div className="flex items-start justify-between gap-3">
                    <div className="min-w-0 flex-1">
                      <div className="mb-1 flex flex-wrap items-center gap-2 text-[11px]">
                        <span className="inline-flex items-center gap-1 rounded-full bg-neutral-100 px-2 py-0.5 font-semibold text-neutral-600">
                          <span aria-hidden>{cat.icon}</span> {cat.label}
                        </span>
                        <StatusBadge status={t.status} />
                      </div>
                      <h2 className="truncate text-base font-bold text-neutral-900 sm:text-lg">
                        {t.title}
                      </h2>
                      <p className="mt-1 flex items-center gap-1 truncate text-xs text-neutral-500 sm:text-sm">
                        <CalendarDays
                          size={14}
                          strokeWidth={1.75}
                          aria-hidden
                          className="shrink-0"
                        />
                        {formatTripCalendarDateRangeLong(t.date, t.endDate)}
                        <span aria-hidden>·</span>
                        <MapPin
                          size={14}
                          strokeWidth={1.75}
                          aria-hidden
                          className="shrink-0"
                        />
                        {t.location}
                      </p>
                      <p className="mt-1 text-xs text-neutral-500 sm:text-sm">
                        Organizer:{" "}
                        <span className="font-semibold text-neutral-700">
                          {t.organizer.name}
                        </span>{" "}
                        <span className="text-neutral-400">
                          ({t.organizer.email})
                        </span>
                      </p>
                    </div>
                    <div className="shrink-0 text-right">
                      <p className="text-sm font-bold text-primary-700 sm:text-base">
                        {formatRupiah(t.price)}
                      </p>
                      <p className="mt-1 text-[11px] text-neutral-500">
                        {t._count.participants}/{t.maxParticipants} peserta
                      </p>
                      <p className="text-[11px] text-emerald-700">
                        {t._count.bookings} PAID
                      </p>
                    </div>
                  </div>
                </Link>
              </li>
            );
          })}
        </ul>
      )}
    </div>
  );
}

function StatusBadge({ status }: { status: string }) {
  const cls =
    status === "OPEN"
      ? "bg-emerald-100 text-emerald-800"
      : status === "FULL"
        ? "bg-amber-100 text-amber-800"
        : status === "CLOSED"
          ? "bg-red-100 text-red-800"
          : "bg-neutral-200 text-neutral-700";
  return (
    <span
      className={`rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide ${cls}`}
    >
      {status}
    </span>
  );
}
