"use client";

import { useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import {
  LayoutDashboard,
  Map,
  Plane,
  CalendarDays,
  FileText,
  Building2,
  Image as ImageIcon,
  Users,
  Mail,
  Settings,
  X,
  Car,
  MapPin,
  Percent,
  MessageSquareQuote,
  ChevronDown,
  Compass,
  Megaphone,
  UserCog,
} from "lucide-react";

interface AdminSidebarProps {
  isOpen: boolean;
  onClose: () => void;
}

interface MenuLeaf {
  name: string;
  href: string;
  icon: typeof LayoutDashboard;
  exact?: boolean;
}

interface MenuGroup {
  name: string;
  icon: typeof LayoutDashboard;
  children: MenuLeaf[];
}

const dashboardItem: MenuLeaf = {
  name: "Dashboard",
  href: "/admin",
  icon: LayoutDashboard,
  exact: true,
};

const menuGroups: MenuGroup[] = [
  {
    name: "Layanan Wisata",
    icon: Compass,
    children: [
      { name: "Paket Tour", href: "/admin/tours", icon: Map },
      { name: "Destinasi Populer", href: "/admin/destinations", icon: MapPin },
      { name: "Tiket Pesawat", href: "/admin/flights", icon: Plane },
      { name: "Event", href: "/admin/events", icon: CalendarDays },
      { name: "Sewa Mobil", href: "/admin/car-rentals", icon: Car },
    ],
  },
  {
    name: "Konten & Promosi",
    icon: Megaphone,
    children: [
      { name: "Artikel", href: "/admin/articles", icon: FileText },
      { name: "Promo Banner", href: "/admin/promos", icon: Percent },
      { name: "Testimoni", href: "/admin/testimonials", icon: MessageSquareQuote },
      { name: "Galeri", href: "/admin/galleries", icon: ImageIcon },
      { name: "Hero Images", href: "/admin/hero-images", icon: ImageIcon },
    ],
  },
  {
    name: "Perusahaan",
    icon: Building2,
    children: [
      { name: "Klien & Mitra", href: "/admin/clients", icon: Building2 },
      { name: "Tim Profesional", href: "/admin/team-members", icon: Users },
    ],
  },
  {
    name: "Komunikasi",
    icon: Mail,
    children: [
      { name: "Pesan Masuk", href: "/admin/contact-messages", icon: Mail },
      { name: "Template WhatsApp", href: "/admin/whatsapp-templates", icon: MessageSquareQuote },
    ],
  },
  {
    name: "Sistem",
    icon: UserCog,
    children: [
      { name: "Pengguna", href: "/admin/users", icon: Users },
      { name: "Pengaturan", href: "/admin/settings", icon: Settings },
    ],
  },
];

export default function AdminSidebar({ isOpen, onClose }: AdminSidebarProps) {
  const pathname = usePathname();

  const isActive = (href: string, exact?: boolean) =>
    exact ? pathname === href : pathname.startsWith(href);

  const groupHasActive = (group: MenuGroup) =>
    group.children.some((c) => isActive(c.href));

  const [openGroups, setOpenGroups] = useState<Record<string, boolean>>(() => {
    const initial: Record<string, boolean> = {};
    for (const group of menuGroups) {
      initial[group.name] = groupHasActive(group);
    }
    return initial;
  });

  const toggleGroup = (name: string) => {
    setOpenGroups((prev) => ({ ...prev, [name]: !prev[name] }));
  };

  return (
    <aside
      className={`fixed inset-y-0 left-0 z-50 w-64 flex flex-col transform transition-transform duration-300 lg:translate-x-0 ${
        isOpen ? "translate-x-0" : "-translate-x-full"
      }`}
      style={{
        background: "linear-gradient(160deg, #1c0a0a 0%, #6f0f0c 50%, #991612 100%)",
      }}
    >
      <div className="flex items-center justify-between h-20 px-6 border-b border-white/10 shrink-0">
        <Link href="/admin" className="font-semibold text-2xl tracking-tight text-white">
          RANATA<span className="text-white/70">ADMIN</span>
        </Link>
        <button
          className="lg:hidden text-white/70 hover:text-white"
          onClick={onClose}
        >
          <X className="w-6 h-6" />
        </button>
      </div>

      <div className="flex-1 overflow-y-auto py-6 px-4 space-y-1">
        <Link
          href={dashboardItem.href}
          onClick={onClose}
          className={`flex items-center px-4 py-3 rounded-xl transition-all duration-200 relative overflow-hidden ${
            isActive(dashboardItem.href, dashboardItem.exact)
              ? "bg-white/95 text-merah-ranata font-semibold shadow-[0_2px_10px_rgba(0,0,0,0.25)]"
              : "text-white/80 hover:bg-white/10 hover:text-white hover:translate-x-0.5"
          }`}
        >
          {isActive(dashboardItem.href, dashboardItem.exact) && (
            <span className="absolute left-0 top-1/2 -translate-y-1/2 h-4/5 w-[3px] rounded-r-full bg-merah-ranata" />
          )}
          <dashboardItem.icon
            className={`w-5 h-5 mr-3 ${
              isActive(dashboardItem.href, dashboardItem.exact) ? "text-merah-ranata" : "text-white/70"
            }`}
          />
          <span className="text-sm">{dashboardItem.name}</span>
          {isActive(dashboardItem.href, dashboardItem.exact) && (
            <span className="absolute right-3 w-1.5 h-1.5 rounded-full bg-merah-ranata" />
          )}
        </Link>

        <div className="pt-3 space-y-1">
          {menuGroups.map((group) => {
            const open = openGroups[group.name];
            const hasActive = groupHasActive(group);
            return (
              <div key={group.name}>
                <button
                  type="button"
                  onClick={() => toggleGroup(group.name)}
                  className={`w-full flex items-center px-4 py-3 rounded-xl transition-colors duration-200 ${
                    hasActive
                      ? "text-white font-semibold bg-white/10 backdrop-blur-sm ring-1 ring-white/10"
                      : "text-white/70 hover:bg-white/5 hover:text-white"
                  }`}
                >
                  <group.icon className={`w-5 h-5 mr-3 shrink-0 ${hasActive ? "text-white" : "text-white/50"}`} />
                  <span className="text-sm flex-1 text-left uppercase tracking-wide text-[11px] font-bold">
                    {group.name}
                  </span>
                  <ChevronDown
                    className={`w-4 h-4 shrink-0 transition-transform duration-300 ease-out ${open ? "rotate-180" : ""}`}
                  />
                </button>

                <div
                  className="grid transition-[grid-template-rows] duration-300 ease-out"
                  style={{ gridTemplateRows: open ? "1fr" : "0fr" }}
                >
                  <div className="overflow-hidden">
                    <div className="mt-1 ml-4 pl-3 border-l border-white/10 space-y-1 py-0.5">
                      {group.children.map((item) => {
                        const active = isActive(item.href);
                        return (
                          <Link
                            key={item.name}
                            href={item.href}
                            onClick={onClose}
                            className={`flex items-center px-3 py-2.5 rounded-lg transition-all duration-200 relative overflow-hidden ${
                              active
                                ? "bg-white/95 text-merah-ranata font-semibold shadow-[0_2px_10px_rgba(0,0,0,0.25)] translate-x-0.5"
                                : "text-white/70 hover:bg-white/10 hover:text-white hover:translate-x-0.5"
                            }`}
                          >
                            {active && (
                              <span className="absolute left-0 top-1/2 -translate-y-1/2 h-4/5 w-[3px] rounded-r-full bg-merah-ranata" />
                            )}
                            <item.icon className={`w-4 h-4 mr-2.5 shrink-0 ${active ? "text-merah-ranata" : "text-white/60"}`} />
                            <span className="text-sm">{item.name}</span>
                            {active && (
                              <span className="absolute right-3 w-1.5 h-1.5 rounded-full bg-merah-ranata" />
                            )}
                          </Link>
                        );
                      })}
                    </div>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </aside>
  );
}
