"use client";

import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { useEffect } from "react";
import { Logo } from "@/components/brand/logo";
import { cn } from "@/lib/utils";
import { AdminQueryProvider } from "./providers";
import { useAuthStore } from "@/stores/auth";

const navItems = [
  { href: "/admin", label: "Dashboard" },
  { href: "/admin/disputes", label: "Disputes" },
  { href: "/admin/inbox", label: "Inbox" },
  { href: "/admin/stores", label: "Stores" },
  { href: "/admin/orders", label: "Orders" },
  { href: "/admin/returns", label: "Returns" },
  { href: "/admin/reviews", label: "Reviews" },
  { href: "/admin/balances", label: "Balances" },
  { href: "/admin/payouts", label: "Failed payouts" },
  { href: "/admin/activity", label: "Activity" },
];

export default function AdminLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const pathname = usePathname();
  const router = useRouter();
  const { user, isLoading } = useAuthStore();

  // Gate the entire admin shell. Without this, non-admins (e.g. a seller
  // navigating to /admin/balances) see the admin sidebar + a 403 from the API,
  // which looks like a broken admin page rather than an access-denied state.
  const isAdmin = !!user?.roles?.includes('admin');

  useEffect(() => {
    if (isLoading) return;
    if (!user) {
      router.replace('/login');
      return;
    }
    if (!isAdmin) {
      router.replace('/seller');
    }
  }, [isLoading, user, isAdmin, router]);

  if (isLoading || !user) {
    return (
      <div
        className="flex min-h-screen items-center justify-center text-sm text-slate-500"
        data-testid="admin-layout-loading"
      >
        Loading…
      </div>
    );
  }

  if (!isAdmin) {
    // Render nothing while the redirect lands — avoids a flash of admin chrome.
    return (
      <div
        className="flex min-h-screen items-center justify-center text-sm text-slate-500"
        data-testid="admin-layout-forbidden"
      >
        Redirecting…
      </div>
    );
  }

  return (
    <AdminQueryProvider>
    <div className="flex min-h-screen">
      <aside className="w-64 bg-slate-900 p-6 shrink-0">
        <Link href="/admin" className="block">
          <Logo variant="inverse" height={24} />
        </Link>
        <p className="text-xs text-slate-500 mt-0.5">Platform Admin</p>
        <nav className="mt-8 flex flex-col gap-1">
          {navItems.map((item) => {
            const isActive = pathname === item.href;
            return (
              <Link
                key={item.href}
                href={item.href}
                className={cn(
                  "text-sm font-medium px-3 py-2 rounded transition-colors",
                  isActive
                    ? "text-forest-200 bg-slate-800 border-l-2 border-forest-200"
                    : "text-slate-400 hover:text-white hover:bg-slate-800"
                )}
              >
                {item.label}
              </Link>
            );
          })}
        </nav>
      </aside>
      <main className="flex-1 bg-slate-50 p-8">{children}</main>
    </div>
    </AdminQueryProvider>
  );
}
