import Link from "next/link";
import Image from "next/image";
import { notFound, redirect } from "next/navigation";
import { getServerSession } from "next-auth";
import { ArrowLeft, ArrowUpRight, Ban, Check } from "lucide-react";
import { authOptions } from "@/lib/auth";
import { isAdminEmail } from "@/lib/admin";
import { userRepo } from "@/server/repositories/user.repo";
import { formatRupiah } from "@/lib/utils";
import { SuspendUserButton } from "@/features/admin/components/suspend-user-button";
import { ManualVerifyButton } from "@/features/admin/components/manual-verify-button";

interface PageProps {
  params: Promise<{ id: string }>;
}

export default async function AdminUserDetailPage({ params }: 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 { id } = await params;
  const user = await userRepo.findByIdForAdmin(id);
  if (!user) notFound();

  const isSelf = user.id === session.user.id;
  const totalSpent = user.bookings
    .filter((b) => b.status === "PAID" || b.status === "PARTIALLY_REFUNDED")
    .reduce((sum, b) => sum + b.amount, 0);

  return (
    <div className="mx-auto max-w-4xl px-4 py-8 sm:py-12">
      <div className="mb-4 text-xs text-neutral-500">
        <Link
          href="/admin/users"
          className="inline-flex items-center gap-1 hover:text-primary-600"
        >
          <ArrowLeft size={14} strokeWidth={2} aria-hidden />
          Kembali ke list users
        </Link>
      </div>

      <header
        className={`mb-6 rounded-2xl border p-5 shadow-sm sm:p-6 ${
          user.suspended
            ? "border-red-300 bg-red-50/60"
            : "border-neutral-200 bg-white"
        }`}
      >
        <div className="flex flex-wrap items-start gap-4">
          {user.image ? (
            <Image
              src={user.image}
              alt=""
              width={64}
              height={64}
              className="h-16 w-16 shrink-0 rounded-full object-cover"
            />
          ) : (
            <div className="flex h-16 w-16 shrink-0 items-center justify-center rounded-full bg-primary-600 text-xl font-bold text-white">
              {user.name.charAt(0).toUpperCase()}
            </div>
          )}
          <div className="min-w-0 flex-1">
            <div className="flex flex-wrap items-center gap-2">
              <h1 className="text-xl font-bold text-neutral-900 sm:text-2xl">
                {user.name}
              </h1>
              {user.suspended && (
                <span className="rounded-full bg-red-100 px-2 py-0.5 text-[11px] font-bold uppercase tracking-wide text-red-800">
                  Suspended
                </span>
              )}
              {user.organizerVerification?.status === "APPROVED" && (
                <span className="inline-flex items-center gap-1 rounded-full bg-emerald-100 px-2 py-0.5 text-[11px] font-bold uppercase tracking-wide text-emerald-800">
                  <Check size={12} strokeWidth={2.5} aria-hidden />
                  Verified Organizer
                </span>
              )}
            </div>
            <p className="mt-0.5 text-sm text-neutral-600">{user.email}</p>
            <p className="mt-0.5 text-[11px] text-neutral-500">
              User ID:{" "}
              <code className="rounded bg-neutral-100 px-1.5 py-0.5 font-mono text-neutral-700">
                {user.id}
              </code>
            </p>
            <p className="mt-1 text-xs text-neutral-500">
              Bergabung{" "}
              {user.createdAt.toLocaleDateString("id-ID", {
                day: "numeric",
                month: "long",
                year: "numeric",
              })}
              {user.acceptedAt && (
                <>
                  {" "}
                  · Setuju T&C{" "}
                  {user.acceptedAt.toLocaleDateString("id-ID", {
                    day: "numeric",
                    month: "short",
                    year: "numeric",
                  })}
                </>
              )}
            </p>
          </div>
        </div>
      </header>

      <section className="mb-6 grid gap-3 sm:grid-cols-3">
        <StatCard label="Trip dibuat" value={String(user.trips.length)} />
        <StatCard label="Booking aktif" value={String(user.bookings.length)} />
        <StatCard
          label="Total spent (PAID)"
          value={formatRupiah(totalSpent)}
          accent="emerald"
        />
      </section>

      {user.suspended && (
        <section className="mb-6 rounded-2xl border border-red-300 bg-red-50 p-4 sm:p-5">
          <h2 className="flex items-center gap-1.5 text-sm font-bold text-red-900">
            <Ban size={16} strokeWidth={2} aria-hidden />
            Akun ditangguhkan
          </h2>
          <p className="mt-1 text-xs text-red-900/80">
            {user.suspendedReason ?? "Tidak ada alasan tercatat."}
          </p>
          {user.suspendedBy && (
            <p className="mt-2 text-[11px] text-red-900/70">
              Disuspend oleh {user.suspendedBy.email}
              {user.suspendedAt && (
                <>
                  {" "}
                  pada{" "}
                  {user.suspendedAt.toLocaleString("id-ID", {
                    day: "2-digit",
                    month: "short",
                    year: "numeric",
                    hour: "2-digit",
                    minute: "2-digit",
                  })}
                </>
              )}
            </p>
          )}
        </section>
      )}

      <section className="mb-6 rounded-2xl border border-neutral-200 bg-white p-4 shadow-sm sm:p-5">
        <h2 className="mb-3 text-sm font-bold text-neutral-900">
          Aksi Admin
        </h2>
        {isSelf ? (
          <p className="text-xs text-neutral-500">
            Tidak bisa suspend / modifikasi akun sendiri.
          </p>
        ) : (
          <div className="flex flex-wrap items-start gap-3">
            <SuspendUserButton userId={user.id} isSuspended={user.suspended} />
            {!user.organizerVerification && (
              <ManualVerifyButton
                userId={user.id}
                defaultBankAccountName={user.name}
              />
            )}
          </div>
        )}
      </section>

      {user.profile && (
        <section className="mb-6 rounded-2xl border border-neutral-200 bg-white p-4 shadow-sm sm:p-5">
          <h2 className="mb-3 text-xs font-bold uppercase tracking-wide text-neutral-500">
            Profil Sosial
          </h2>
          <dl className="grid gap-3 text-sm sm:grid-cols-2">
            {user.profile.bio && (
              <div className="sm:col-span-2">
                <dt className="text-[10px] font-semibold uppercase tracking-wide text-neutral-500">
                  Bio
                </dt>
                <dd className="whitespace-pre-wrap text-neutral-700">
                  {user.profile.bio}
                </dd>
              </div>
            )}
            {user.profile.city && (
              <div>
                <dt className="text-[10px] font-semibold uppercase tracking-wide text-neutral-500">
                  Kota
                </dt>
                <dd className="text-neutral-700">{user.profile.city}</dd>
              </div>
            )}
            {user.profile.vibe && (
              <div>
                <dt className="text-[10px] font-semibold uppercase tracking-wide text-neutral-500">
                  Vibe
                </dt>
                <dd className="text-neutral-700">{user.profile.vibe}</dd>
              </div>
            )}
            {user.profile.interests.length > 0 && (
              <div className="sm:col-span-2">
                <dt className="text-[10px] font-semibold uppercase tracking-wide text-neutral-500">
                  Minat
                </dt>
                <dd className="mt-0.5 flex flex-wrap gap-1.5">
                  {user.profile.interests.map((tag) => (
                    <span
                      key={tag}
                      className="rounded-full bg-secondary-50 px-2 py-0.5 text-[11px] font-medium text-secondary-700"
                    >
                      #{tag}
                    </span>
                  ))}
                </dd>
              </div>
            )}
            {user.profile.instagram && (
              <div>
                <dt className="text-[10px] font-semibold uppercase tracking-wide text-neutral-500">
                  Instagram
                </dt>
                <dd className="text-neutral-700">@{user.profile.instagram}</dd>
              </div>
            )}
          </dl>
        </section>
      )}

      {user.organizerVerification && (
        <section className="mb-6 rounded-2xl border border-neutral-200 bg-white p-4 shadow-sm sm:p-5">
          <h2 className="mb-3 text-xs font-bold uppercase tracking-wide text-neutral-500">
            Verifikasi Organizer
          </h2>
          <p className="text-sm text-neutral-700">
            Status:{" "}
            <span className="font-semibold">
              {user.organizerVerification.status}
            </span>
            {" · "}
            <Link
              href={`/admin/verifications?tab=${user.organizerVerification.status}`}
              className="inline-flex items-center gap-1 text-secondary-700 hover:text-secondary-900"
            >
              Buka di /admin/verifications
              <ArrowUpRight size={14} strokeWidth={2} aria-hidden />
            </Link>
          </p>
          {user.organizerVerification.rejectionReason && (
            <p className="mt-1 text-xs text-red-700">
              Reason: {user.organizerVerification.rejectionReason}
            </p>
          )}
        </section>
      )}

      <section className="mb-6 rounded-2xl border border-neutral-200 bg-white p-4 shadow-sm sm:p-5">
        <h2 className="mb-3 text-xs font-bold uppercase tracking-wide text-neutral-500">
          Trip yang dibuat ({user.trips.length})
        </h2>
        {user.trips.length === 0 ? (
          <p className="text-xs text-neutral-500">
            User ini belum pernah membuat trip.
          </p>
        ) : (
          <ul className="divide-y divide-neutral-100">
            {user.trips.map((t) => (
              <li key={t.id} className="py-2.5">
                <Link
                  href={`/admin/trips/${t.id}`}
                  className="flex items-center justify-between gap-3 text-sm hover:text-primary-700"
                >
                  <div className="min-w-0 flex-1">
                    <p className="truncate font-semibold text-neutral-800">
                      {t.title}
                    </p>
                    <p className="text-[11px] text-neutral-500">
                      {t.destination} ·{" "}
                      {t.date.toLocaleDateString("id-ID", {
                        day: "numeric",
                        month: "short",
                        year: "numeric",
                      })}{" "}
                      · {t.status}
                    </p>
                  </div>
                  <p className="shrink-0 text-xs font-semibold text-primary-700">
                    {formatRupiah(t.price)}
                  </p>
                </Link>
              </li>
            ))}
          </ul>
        )}
      </section>

      <section className="mb-6 rounded-2xl border border-neutral-200 bg-white p-4 shadow-sm sm:p-5">
        <h2 className="mb-3 text-xs font-bold uppercase tracking-wide text-neutral-500">
          Booking sebagai peserta ({user.bookings.length})
        </h2>
        {user.bookings.length === 0 ? (
          <p className="text-xs text-neutral-500">Belum ada booking.</p>
        ) : (
          <ul className="divide-y divide-neutral-100">
            {user.bookings.map((b) => (
              <li key={b.id} className="py-2.5">
                <Link
                  href={`/admin/bookings/${b.id}`}
                  className="flex items-center justify-between gap-3 text-sm hover:text-primary-700"
                >
                  <div className="min-w-0 flex-1">
                    <p className="truncate font-semibold text-neutral-800">
                      {b.trip.title}
                    </p>
                    <p className="text-[11px] text-neutral-500">
                      {b.trip.date.toLocaleDateString("id-ID", {
                        day: "numeric",
                        month: "short",
                        year: "numeric",
                      })}{" "}
                      · status: <span className="font-semibold">{b.status}</span>
                    </p>
                  </div>
                  <p className="shrink-0 text-xs font-semibold text-primary-700">
                    {formatRupiah(b.amount)}
                  </p>
                </Link>
              </li>
            ))}
          </ul>
        )}
      </section>
    </div>
  );
}

function StatCard({
  label,
  value,
  accent = "primary",
}: {
  label: string;
  value: string;
  accent?: "primary" | "emerald";
}) {
  const cls = accent === "emerald" ? "text-emerald-700" : "text-primary-700";
  return (
    <div className="rounded-xl border border-neutral-200 bg-white p-3 sm:p-4">
      <p className="text-[10px] font-semibold uppercase tracking-wide text-neutral-500">
        {label}
      </p>
      <p className={`mt-0.5 text-lg font-bold sm:text-xl ${cls}`}>{value}</p>
    </div>
  );
}
