import Link from "next/link";
import Image from "next/image";
import { redirect } from "next/navigation";
import { getServerSession } from "next-auth";
import { Check, ChartColumn } from "lucide-react";
import { authOptions } from "@/lib/auth";
import { isAdminEmail } from "@/lib/admin";
import { userRepo } from "@/server/repositories/user.repo";

type Tab = "ALL" | "ACTIVE" | "SUSPENDED";

const TABS: { key: Tab; label: string }[] = [
  { key: "ALL", label: "Semua" },
  { key: "ACTIVE", label: "Aktif" },
  { key: "SUSPENDED", label: "Suspended" },
];

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

export default async function AdminUsersPage({ searchParams }: PageProps) {
  const session = await getServerSession(authOptions);
  if (!session?.user) redirect("/login?callbackUrl=/admin/users");
  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 users = await userRepo.searchForAdmin({
    q: q || undefined,
    suspended: tab === "SUSPENDED" ? true : tab === "ACTIVE" ? false : undefined,
  });

  return (
    <div className="mx-auto max-w-5xl 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">
            User Management
          </h1>
          <p className="mt-1 text-sm text-neutral-500">
            Cari user, lihat history booking & trip, dan suspend akun yang
            melakukan abuse (scam, harassment, TOS violation).
          </p>
        </div>
        <Link
          href="/admin/users/stats"
          className="inline-flex items-center gap-1.5 rounded-xl border border-neutral-200 bg-white px-3 py-1.5 text-xs font-semibold text-neutral-700 hover:bg-neutral-50"
        >
          <ChartColumn size={16} strokeWidth={2} aria-hidden />
          Stats
        </Link>
      </header>

      <form method="get" className="mb-4 flex gap-2">
        <input type="hidden" name="tab" value={tab} />
        <input
          name="q"
          defaultValue={q}
          placeholder="Cari email atau nama..."
          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/users?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/users?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>

      {users.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 user yang cocok dengan "${q}".`
              : "Tidak ada user pada tab ini."}
          </p>
        </div>
      ) : (
        <ul className="space-y-2">
          {users.map((u) => (
            <li
              key={u.id}
              className={`rounded-2xl border bg-white p-3 shadow-sm transition-shadow hover:shadow-md sm:p-4 ${
                u.suspended ? "border-red-200" : "border-neutral-200"
              }`}
            >
              <Link
                href={`/admin/users/${u.id}`}
                className="flex items-center gap-3"
              >
                {u.image ? (
                  <Image
                    src={u.image}
                    alt=""
                    width={40}
                    height={40}
                    className="h-10 w-10 shrink-0 rounded-full object-cover"
                  />
                ) : (
                  <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-primary-600 text-sm font-bold text-white">
                    {u.name.charAt(0).toUpperCase()}
                  </div>
                )}
                <div className="min-w-0 flex-1">
                  <div className="flex flex-wrap items-center gap-2">
                    <p className="truncate text-sm font-semibold text-neutral-800">
                      {u.name}
                    </p>
                    {u.suspended && (
                      <span className="rounded-full bg-red-100 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide text-red-800">
                        Suspended
                      </span>
                    )}
                    {u.organizerVerification?.status === "APPROVED" && (
                      <span className="inline-flex items-center gap-1 rounded-full bg-emerald-100 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide text-emerald-800">
                        <Check size={12} strokeWidth={2.5} aria-hidden />
                        Organizer
                      </span>
                    )}
                  </div>
                  <p className="truncate text-xs text-neutral-500">{u.email}</p>
                  <p className="mt-0.5 text-[11px] text-neutral-400">
                    Bergabung{" "}
                    {u.createdAt.toLocaleDateString("id-ID", {
                      day: "numeric",
                      month: "short",
                      year: "numeric",
                    })}
                    {" · "}
                    {u._count.trips} trip dibuat, {u._count.participations}{" "}
                    booking
                  </p>
                </div>
              </Link>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}
