"use client";

import { useEffect, useState } from "react";
import { usePathname, useRouter } from "next/navigation";
import Link from "next/link";
import { AnimatePresence, motion } from "framer-motion";
import {
  LayoutDashboard,
  Users,
  BarChart3,
  LogOut,
  Menu,
  X,
  Gauge,
  FileText,
  Tag,
  TrendingUp,
  ShieldCheck,
  Bell,
  LineChart,
  BadgeCheck,
  ShieldAlert,
  Sparkles,
  Swords,
  Newspaper,
  DollarSign,
  ClipboardCheck,
  Bot,
  Image as ImageIcon,
  Megaphone,
  Images,
  ChevronDown,
  Car,
  Globe,
  Map,
  Cpu,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { getAdminToken, clearAdminToken } from "@/lib/adminAuth";

// ── Navigation structure (grouped) ─────────────────────────────────────────────

const NAV_GROUPS = [
  {
    group: "Dashboard",
    collapsible: false,
    items: [
      { label: "Dashboard",         href: "/admin",                  icon: LayoutDashboard },
    ],
  },
  {
    group: "Cars",
    collapsible: true,
    items: [
      { label: "Cars",              href: "/admin/enrichment",        icon: Car },
      { label: "Brands",            href: "/admin/brands",            icon: Tag },
      { label: "Car Images",        href: "/admin/cars/images",       icon: Images },
      { label: "Price Tracking",    href: "/admin/prices",            icon: DollarSign },
      { label: "Best Cars",         href: "/admin/best-cars",         icon: TrendingUp },
      { label: "Rivals",            href: "/admin/rivals",            icon: Swords },
    ],
  },
  {
    group: "Content",
    collapsible: true,
    items: [
      { label: "Blogs",             href: "/admin/blogs",             icon: FileText },
      { label: "News",              href: "/admin/news",              icon: Newspaper },
    ],
  },
  {
    group: "SEO",
    collapsible: true,
    items: [
      { label: "SEO Health",        href: "/admin/seo-health",        icon: ShieldCheck },
      { label: "Moderation",        href: "/admin/moderation",        icon: ShieldAlert },
      { label: "Confidence",        href: "/admin/confidence",        icon: BadgeCheck },
    ],
  },
  {
    group: "AI",
    collapsible: true,
    items: [
      { label: "AI Generator",      href: "/admin/ai-generator",      icon: Cpu },
      { label: "AI Providers",      href: "/admin/ai-settings",       icon: Bot },
      { label: "Data Quality",      href: "/admin/enrichment",        icon: Sparkles },
    ],
  },
  {
    group: "Analytics",
    collapsible: true,
    items: [
      { label: "Analytics",         href: "/admin/analytics",         icon: BarChart3 },
      { label: "Leads",             href: "/admin/leads",             icon: Users },
      { label: "Lead Intelligence", href: "/admin/lead-intelligence", icon: LineChart },
      { label: "Reports",           href: "/admin/report",            icon: ClipboardCheck },
      { label: "Alerts",            href: "/admin/alerts",            icon: Bell },
    ],
  },
  {
    group: "Settings",
    collapsible: true,
    items: [
      { label: "Banners",           href: "/admin/banners",           icon: ImageIcon },
      { label: "Ads",               href: "/admin/ads",               icon: Megaphone },
      { label: "Media Library",     href: "/admin/media",             icon: Images },
    ],
  },
];

// ── Group section component ─────────────────────────────────────────────────────

function NavGroup({
  group,
  collapsible,
  items,
  pathname,
  onLinkClick,
}: {
  group: string;
  collapsible: boolean;
  items: { label: string; href: string; icon: React.ComponentType<{ className?: string }> }[];
  pathname: string;
  onLinkClick?: () => void;
}) {
  const groupActive = items.some((item) =>
    item.href === "/admin" ? pathname === "/admin" : pathname.startsWith(item.href)
  );
  const [open, setOpen] = useState(!collapsible || groupActive);

  return (
    <div className="mb-1">
      {group !== "Dashboard" && (
        <button
          onClick={() => collapsible && setOpen((o) => !o)}
          className={cn(
            "w-full flex items-center justify-between px-3 py-1.5 rounded-lg text-[10px] font-black uppercase tracking-widest transition-colors",
            groupActive ? "text-blue-500" : "text-gray-400 hover:text-gray-600",
            !collapsible && "cursor-default"
          )}
        >
          {group}
          {collapsible && (
            <ChevronDown className={cn("w-3 h-3 transition-transform duration-200", open && "rotate-180")} />
          )}
        </button>
      )}

      <AnimatePresence initial={false}>
        {(!collapsible || open) && (
          <motion.div
            initial={collapsible ? { height: 0, opacity: 0 } : false}
            animate={{ height: "auto", opacity: 1 }}
            exit={collapsible ? { height: 0, opacity: 0 } : undefined}
            transition={{ duration: 0.2 }}
            className="overflow-hidden"
          >
            <div className="space-y-0.5">
              {items.map(({ label, href, icon: Icon }) => {
                const isActive =
                  href === "/admin"
                    ? pathname === "/admin"
                    : pathname.startsWith(href);
                return (
                  <Link
                    key={`${href}-${label}`}
                    href={href}
                    onClick={onLinkClick}
                    className={cn(
                      "flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm font-semibold transition-all duration-150",
                      isActive
                        ? "bg-gradient-to-r from-blue-600 to-cyan-500 text-white shadow-md shadow-blue-200/50"
                        : "text-gray-600 hover:bg-gray-100 hover:text-gray-900"
                    )}
                  >
                    <Icon className="w-4 h-4 shrink-0" />
                    <span className="truncate">{label}</span>
                  </Link>
                );
              })}
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}

// ── Sidebar content ─────────────────────────────────────────────────────────────

function SidebarContent({
  pathname,
  onLogout,
  onLinkClick,
}: {
  pathname: string;
  onLogout: () => void;
  onLinkClick?: () => void;
}) {
  return (
    <>
      {/* Logo */}
      <div className="flex items-center gap-3 px-4 py-5 border-b border-gray-100 shrink-0">
        <div className="w-9 h-9 rounded-xl bg-gradient-to-br from-blue-600 to-cyan-500 flex items-center justify-center shadow-md">
          <Gauge className="w-5 h-5 text-white" />
        </div>
        <div>
          <p className="text-sm font-black text-gray-900 leading-tight">DriveHub</p>
          <p className="text-[10px] font-bold text-blue-500 uppercase tracking-wider">Admin Panel</p>
        </div>
      </div>

      {/* Nav */}
      <nav className="flex-1 px-3 py-4 overflow-y-auto scrollbar-thin space-y-3" aria-label="Admin navigation">
        {NAV_GROUPS.map(({ group, collapsible, items }) => (
          <NavGroup
            key={group}
            group={group}
            collapsible={collapsible}
            items={items}
            pathname={pathname}
            onLinkClick={onLinkClick}
          />
        ))}
      </nav>

      {/* Logout */}
      <div className="px-3 py-4 border-t border-gray-100 shrink-0">
        <Link
          href="/"
          className="flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm font-semibold text-gray-500 hover:bg-gray-100 hover:text-gray-900 transition-all mb-1"
        >
          <Globe className="w-4 h-4 shrink-0" />
          View Site
        </Link>
        <button
          onClick={onLogout}
          className="w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm font-semibold text-red-500 hover:bg-red-50 transition-all"
        >
          <LogOut className="w-4 h-4 shrink-0" />
          Logout
        </button>
      </div>
    </>
  );
}

// ── Main layout ────────────────────────────────────────────────────────────────

export default function AdminLayout({ children }: { children: React.ReactNode }) {
  const pathname  = usePathname();
  const router    = useRouter();
  const [ready, setReady]           = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);

  useEffect(() => {
    // Login page is always accessible — layout renders it as a pass-through
    if (pathname === "/admin/login") {
      console.log("[ADMIN_AUTH] on login page, skipping token check");
      setReady(true);
      return;
    }

    // getAdminToken() checks sessionStorage first, then falls back to the
    // drivehub_admin_session cookie and syncs it back into sessionStorage.
    // This prevents a redirect loop when the user opens admin in a new tab
    // (sessionStorage is empty but the cookie is present).
    const token = getAdminToken();
    console.log("[ADMIN_AUTH] path=%s token=%s", pathname, token ? "found" : "missing");

    if (!token) {
      console.log("[ADMIN_REDIRECT] %s → /admin/login (no token)", pathname);
      router.replace("/admin/login");
    } else {
      setReady(true);
    }
  // ⚠  Do NOT add `router` to the dependency array.
  // useRouter() in Next.js App Router is stable, but older React versions
  // return a new object on each render.  Having it in deps causes the effect
  // to re-fire on every render, re-reading the token unnecessarily.
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pathname]);

  // Close mobile drawer on route change
  useEffect(() => { setMobileOpen(false); }, [pathname]);

  // Body scroll lock
  useEffect(() => {
    document.body.style.overflow = mobileOpen ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [mobileOpen]);

  function handleLogout() {
    console.log("[ADMIN_AUTH] logout — clearing token");
    clearAdminToken();   // removes sessionStorage key + expires cookie
    router.replace("/admin/login");
  }

  if (pathname === "/admin/login") return <>{children}</>;

  if (!ready) {
    return (
      <div className="min-h-screen bg-[#f5f7fb] flex items-center justify-center">
        <div className="w-8 h-8 rounded-full border-2 border-blue-500 border-t-transparent animate-spin" />
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-[#f5f7fb] flex">

      {/* ── Desktop sidebar ── */}
      <aside className="hidden lg:flex flex-col w-60 shrink-0 bg-white border-r border-gray-100 shadow-sm sticky top-0 h-screen">
        <SidebarContent pathname={pathname} onLogout={handleLogout} />
      </aside>

      {/* ── Mobile drawer backdrop ── */}
      <AnimatePresence>
        {mobileOpen && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="lg:hidden fixed inset-0 z-40 bg-black/40 backdrop-blur-sm"
            onClick={() => setMobileOpen(false)}
          />
        )}
      </AnimatePresence>

      {/* ── Mobile drawer ── */}
      <AnimatePresence>
        {mobileOpen && (
          <motion.aside
            initial={{ x: "-100%" }}
            animate={{ x: 0 }}
            exit={{ x: "-100%" }}
            transition={{ type: "spring", damping: 30, stiffness: 300 }}
            className="lg:hidden fixed top-0 left-0 z-50 w-[min(18rem,85vw)] h-full bg-white border-r border-gray-100 shadow-2xl flex flex-col"
          >
            <div className="flex items-center justify-end px-4 py-3 border-b border-gray-100">
              <button
                onClick={() => setMobileOpen(false)}
                className="p-2 rounded-xl hover:bg-gray-100 transition-colors"
                aria-label="Close navigation"
              >
                <X className="w-5 h-5 text-gray-500" />
              </button>
            </div>
            <div className="flex-1 flex flex-col overflow-hidden">
              <SidebarContent
                pathname={pathname}
                onLogout={handleLogout}
                onLinkClick={() => setMobileOpen(false)}
              />
            </div>
          </motion.aside>
        )}
      </AnimatePresence>

      {/* ── Main content ── */}
      <div className="flex-1 flex flex-col min-w-0">

        {/* Top bar */}
        <header className="bg-white border-b border-gray-100 shadow-sm sticky top-0 z-30">
          <div className="flex items-center justify-between px-4 sm:px-6 py-3.5">
            <div className="flex items-center gap-3">
              <button
                className="lg:hidden p-2 rounded-xl hover:bg-gray-100 transition-colors"
                onClick={() => setMobileOpen(true)}
                aria-label="Open navigation menu"
              >
                <Menu className="w-5 h-5 text-gray-600" />
              </button>
              <div>
                <h1 className="text-sm font-black text-gray-900 leading-tight">
                  DriveHub Admin
                </h1>
                <p className="text-xs text-gray-400 hidden sm:block">
                  {pathname === "/admin"
                    ? "Dashboard"
                    : pathname.split("/").filter(Boolean).slice(1).join(" › ").replace(/-/g, " ")}
                </p>
              </div>
            </div>
            <div className="flex items-center gap-2">
              <Link
                href="/"
                className="hidden sm:flex items-center gap-1.5 text-xs font-semibold text-gray-500 hover:text-gray-700 px-3 py-2 rounded-xl hover:bg-gray-100 transition-all"
              >
                <Globe className="w-3.5 h-3.5" />
                View Site
              </Link>
              <button
                onClick={handleLogout}
                className="flex items-center gap-2 text-sm font-semibold text-red-500 hover:text-red-600 px-3 py-2 rounded-xl hover:bg-red-50 transition-all"
              >
                <LogOut className="w-4 h-4" />
                <span className="hidden sm:inline">Logout</span>
              </button>
            </div>
          </div>
        </header>

        {/* Page content */}
        <main className="flex-1 overflow-auto">
          {children}
        </main>
      </div>
    </div>
  );
}
