"use client";

import * as React from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { motion, AnimatePresence } from "framer-motion";
import { signOut } from "next-auth/react";
import {
  LayoutDashboard, Settings, Wrench, FolderKanban, Repeat, Image as ImageIcon,
  Star, HelpCircle, Users, FileText, Inbox, Quote, Snowflake, Menu, X,
  LogOut, ExternalLink, Building2, Search, ChevronDown,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";

const NAV_GROUPS = [
  {
    label: "Overview",
    items: [{ label: "Dashboard", href: "/admin", icon: LayoutDashboard }],
  },
  {
    label: "Content",
    items: [
      { label: "Services", href: "/admin/services", icon: Wrench },
      { label: "Projects", href: "/admin/projects", icon: FolderKanban },
      { label: "Before / After", href: "/admin/before-after", icon: Repeat },
      { label: "Industries", href: "/admin/industries", icon: Building2 },
      { label: "Blog Posts", href: "/admin/blog", icon: FileText },
      { label: "Testimonials", href: "/admin/testimonials", icon: Star },
      { label: "FAQs", href: "/admin/faq", icon: HelpCircle },
      { label: "Team", href: "/admin/team", icon: Users },
    ],
  },
  {
    label: "Leads",
    items: [
      { label: "All Leads", href: "/admin/leads", icon: Inbox },
      { label: "Quote Requests", href: "/admin/leads?type=QUOTE", icon: Quote },
    ],
  },
  {
    label: "System",
    items: [
      { label: "Media Library", href: "/admin/media", icon: ImageIcon },
      { label: "Settings", href: "/admin/settings", icon: Settings },
    ],
  },
];

export function AdminSidebar({ userEmail }: { userEmail?: string | null }) {
  const pathname = usePathname();
  const [mobileOpen, setMobileOpen] = React.useState(false);

  const isActive = (href: string) => {
    const base = href.split("?")[0];
    if (base === "/admin") return pathname === "/admin";
    return pathname.startsWith(base);
  };

  const SidebarContent = (
    <div className="flex flex-col h-full">
      {/* Brand */}
      <div className="px-5 py-5 border-b border-white/10">
        <Link href="/admin" className="flex items-center gap-3">
          <div className="grid place-items-center size-10 rounded-xl brand-gradient text-white">
            <Snowflake className="size-5" />
          </div>
          <div className="leading-tight">
            <div className="font-extrabold text-white text-sm">AHE Services</div>
            <div className="text-[10px] tracking-[0.16em] text-white/40 uppercase">Admin Panel</div>
          </div>
        </Link>
      </div>

      {/* Nav */}
      <nav className="flex-1 overflow-y-auto px-3 py-4 space-y-6">
        {NAV_GROUPS.map((group) => (
          <div key={group.label}>
            <div className="px-3 mb-2 text-[10px] font-semibold uppercase tracking-[0.14em] text-white/30">
              {group.label}
            </div>
            <div className="space-y-0.5">
              {group.items.map((item) => {
                const active = isActive(item.href);
                return (
                  <Link
                    key={item.href}
                    href={item.href}
                    className={cn(
                      "flex items-center gap-3 px-3 py-2 rounded-lg text-sm transition-colors",
                      active
                        ? "bg-[var(--brand-royal)] text-white font-medium"
                        : "text-white/60 hover:text-white hover:bg-white/5"
                    )}
                  >
                    <item.icon className="size-4 shrink-0" />
                    <span className="truncate">{item.label}</span>
                  </Link>
                );
              })}
            </div>
          </div>
        ))}
      </nav>

      {/* Footer */}
      <div className="px-3 py-4 border-t border-white/10 space-y-1">
        <Link href="/" target="_blank" className="flex items-center gap-3 px-3 py-2 rounded-lg text-sm text-white/60 hover:text-white hover:bg-white/5">
          <ExternalLink className="size-4" /> View Website
        </Link>
        <button
          onClick={() => signOut({ callbackUrl: "/admin/login" })}
          className="w-full flex items-center gap-3 px-3 py-2 rounded-lg text-sm text-white/60 hover:text-white hover:bg-white/5"
        >
          <LogOut className="size-4" /> Sign Out
        </button>
        {userEmail && (
          <div className="px-3 pt-2 text-[11px] text-white/30 truncate">{userEmail}</div>
        )}
      </div>
    </div>
  );

  return (
    <>
      {/* Mobile top bar */}
      <div className="lg:hidden sticky top-0 z-40 navy-bg text-white px-4 py-3 flex items-center justify-between">
        <Link href="/admin" className="flex items-center gap-2">
          <div className="grid place-items-center size-9 rounded-lg brand-gradient">
            <Snowflake className="size-4" />
          </div>
          <span className="font-bold text-sm">AHE Admin</span>
        </Link>
        <button onClick={() => setMobileOpen(true)} className="grid place-items-center size-9 rounded-lg bg-white/10">
          <Menu className="size-5" />
        </button>
      </div>

      {/* Desktop sidebar */}
      <aside className="hidden lg:flex flex-col w-64 shrink-0 navy-bg fixed inset-y-0 left-0 z-30">
        {SidebarContent}
      </aside>

      {/* Mobile drawer */}
      <AnimatePresence>
        {mobileOpen && (
          <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} className="fixed inset-0 z-50 lg:hidden">
            <div className="absolute inset-0 bg-black/50" onClick={() => setMobileOpen(false)} />
            <motion.aside
              initial={{ x: "-100%" }} animate={{ x: 0 }} exit={{ x: "-100%" }}
              transition={{ type: "spring", damping: 30, stiffness: 280 }}
              className="absolute left-0 top-0 bottom-0 w-72 navy-bg"
            >
              <button onClick={() => setMobileOpen(false)} className="absolute top-4 right-4 grid place-items-center size-8 rounded-lg bg-white/10 text-white">
                <X className="size-4" />
              </button>
              {SidebarContent}
            </motion.aside>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  );
}
