/**
 * app/admin/layout.tsx
 * Admin section shell — sidebar, auth guard (admin role only).
 *
 * ADMIN MODULE — fully self-contained. Remove entire /app/admin folder
 * to drop this section without touching any other code.
 */

"use client";

import { useEffect, useState } from "react";
import { useRouter, usePathname } from "next/navigation";
import Link from "next/link";
import { clsx } from "clsx";
import { useAuth } from "@/hooks/useAuth";
import {
  LayoutDashboard,
  Users,
  UserPlus,
  ArrowRightLeft,
  ShoppingBag,
  Percent,
  LogOut,
  Building2,
  Menu,
  X,
  ChevronRight,
  ShieldCheck,
  Wallet,
  Layers,
} from "lucide-react";
import { Loader2 } from "lucide-react";
import toast from "react-hot-toast";

const NAV = [
  { href: "/admin", label: "Overview", icon: LayoutDashboard, exact: true },
  { href: "/admin/agents", label: "Associates", icon: Users, exact: false },
  { href: "/admin/add-agent", label: "Add Associate", icon: UserPlus, exact: false },
  { href: "/admin/transfer", label: "Transfer Agent", icon: ArrowRightLeft, exact: false },
  {
    href: "/admin/team-levels",
    label: "Team Level Wise",
    icon: Layers,
    exact: false,
  },
  { href: "/admin/sales", label: "Sales", icon: ShoppingBag, exact: false },
  {
    href: "/admin/payouts",
    label: "Payout Requests",
    icon: Wallet,
    exact: false,
  },
  {
    href: "/admin/commission-config",
    label: "Commission Rates",
    icon: Percent,
    exact: false,
  },
];

export default function AdminLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const router = useRouter();
  const pathname = usePathname();
  const { user, loading, logout } = useAuth();
  const [sidebarOpen, setSidebarOpen] = useState(false);

  useEffect(() => {
    if (!loading && !user) router.push("/login");
    if (!loading && user && user.role !== "admin") {
      toast.error("Admin access only");
      router.push("/dashboard");
    }
  }, [user, loading, router]);

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-slate-900">
        <Loader2 className="h-8 w-8 animate-spin text-white" />
      </div>
    );
  }

  if (!user || user.role !== "admin") return null;

  const handleLogout = async () => {
    await logout();
    toast.success("Signed out");
    router.push("/");
  };

  const isActive = (href: string, exact: boolean) =>
    exact ? pathname === href : pathname.startsWith(href);

  const SidebarContent = () => (
    <div className="flex flex-col h-full">
      {/* Logo */}
      <div className="px-6 py-8 border-b border-white/5">
        <div className="flex items-center gap-3">
          <div className="h-9 w-9 rounded-xl bg-indigo-600 flex items-center justify-center flex-shrink-0 shadow-lg shadow-indigo-500/20">
            <Building2 className="h-5 w-5 text-white" />
          </div>
          <div>
            <p className="text-white font-black text-sm tracking-tight uppercase leading-none">
              Property Hub
            </p>
            <p className="text-indigo-400 text-[10px] uppercase tracking-widest font-black mt-1">
              Admin Panel
            </p>
          </div>
        </div>
      </div>

      {/* Nav */}
      <nav className="flex-1 px-4 py-6 space-y-2 overflow-y-auto">
        {NAV.map(({ href, label, icon: Icon, exact }) => {
          const active = isActive(href, exact);
          return (
            <Link
              key={href}
              href={href}
              onClick={() => setSidebarOpen(false)}
              className={`flex items-center gap-3 px-4 py-3.5 rounded-2xl text-[10px] font-black uppercase tracking-widest transition-all group ${
                active
                  ? "bg-indigo-600 text-white shadow-lg shadow-indigo-500/20"
                  : "text-slate-400 hover:bg-white/5 hover:text-white"
              }`}
            >
              <Icon
                className={clsx(
                  "h-4 w-4 flex-shrink-0 transition-colors",
                  active
                    ? "text-white"
                    : "text-slate-500 group-hover:text-indigo-400",
                )}
              />
              <span className="flex-1">{label}</span>
              {active && (
                <ChevronRight className="h-3 w-3 text-indigo-200 ml-auto" />
              )}
            </Link>
          );
        })}
      </nav>

      {/* User + Logout */}
      <div className="px-4 py-6 border-t border-white/5 space-y-4">
        <div className="px-4 bg-white/5 py-4 rounded-2xl border border-white/5">
          <p className="text-white text-[10px] font-black uppercase tracking-tight truncate mb-1">
            {user.name}
          </p>
          <p className="text-slate-500 text-[10px] font-bold truncate">
            {user.email}
          </p>
        </div>
        <div className="flex flex-col gap-2">
          <Link
            href="/dashboard"
            className="flex items-center justify-center gap-3 px-4 py-3 rounded-xl text-[10px] font-black uppercase tracking-widest text-indigo-400 bg-indigo-400/10 hover:bg-indigo-400/20 transition-all border border-indigo-400/20"
          >
            <LayoutDashboard className="h-4 w-4" />
            Agent View
          </Link>
          {handleLogout && (
            <div className="flex flex-col gap-2">
              {user.role === "admin" && (
                <Link
                  href="/admin"
                  className="flex w-full items-center justify-center gap-2 rounded-xl py-3 text-[10px] font-black text-indigo-400 bg-indigo-400/10 hover:bg-indigo-400/20 transition-all uppercase tracking-widest border border-indigo-400/20 shadow-sm"
                >
                  <ShieldCheck className="h-3.5 w-3.5" />
                  Admin Control
                </Link>
              )}
              <button
                onClick={handleLogout}
                className="flex w-full items-center justify-center gap-2 rounded-xl py-3 text-[10px] font-black text-slate-500 hover:text-rose-400 hover:bg-rose-500/5 transition-all uppercase tracking-widest border border-transparent hover:border-rose-500/10"
              >
                <LogOut className="h-3.5 w-3.5" />
                Sign out
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  );

  return (
    <div className="flex h-screen bg-slate-50 overflow-hidden">
      {/* Desktop Sidebar */}
      <aside className="hidden md:flex w-64 flex-shrink-0 bg-slate-900 flex-col h-full border-r border-white/5 shadow-[20px_0_40px_rgba(79,70,229,0.1)]">
        <SidebarContent />
      </aside>

      {/* Mobile Sidebar Overlay */}
      {sidebarOpen && (
        <div className="md:hidden fixed inset-0 z-50 flex">
          <div
            className="absolute inset-0 bg-slate-900/60 backdrop-blur-sm"
            onClick={() => setSidebarOpen(false)}
          />
          <aside className="relative w-64 bg-slate-900 h-full flex flex-col z-10 border-r border-white/5">
            <SidebarContent />
          </aside>
        </div>
      )}

      {/* Main */}
      <div className="flex-1 flex flex-col overflow-hidden">
        {/* Mobile header */}
        <div className="md:hidden flex items-center gap-3 px-4 py-3 bg-white/90 backdrop-blur-xl border-b border-slate-100">
          <button
            onClick={() => setSidebarOpen(true)}
            className="p-2 rounded-lg hover:bg-slate-50 transition-colors"
          >
            <Menu className="h-5 w-5 text-slate-900" />
          </button>
          <span className="font-black text-slate-900 text-[10px] uppercase tracking-widest">
            Admin Control
          </span>
        </div>

        <main className="flex-1 overflow-y-auto p-4 md:p-8">
          <div className="max-w-7xl mx-auto">{children}</div>
        </main>
      </div>
    </div>
  );
}
