"use client";

import { useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import {
  HomeIcon,
  FolderIcon,
  ImageIcon,
  LayersIcon,
  MessageIcon,
  BarChartIcon,
  SettingsIcon,
  LogOutIcon,
  CodeIcon,
  PlusIcon,
  ChevronDownIcon,
} from "@/components/Icons";

interface NavItem {
  label: string;
  href?: string;
  icon: React.ComponentType<{ size?: number; className?: string }>;
  badge?: number;
  children?: { label: string; href: string }[];
}

const navigation: NavItem[] = [
  { label: "Dashboard", href: "/admin/dashboard", icon: HomeIcon },
  {
    label: "Projects",
    icon: FolderIcon,
    children: [
      { label: "All Projects", href: "/admin/projects" },
      { label: "Add New", href: "/admin/projects/new" },
      { label: "Categories", href: "/admin/categories" },
    ],
  },
  {
    label: "Media",
    icon: ImageIcon,
    children: [
      { label: "All Media", href: "/admin/media" },
      { label: "Upload", href: "/admin/media/upload" },
    ],
  },
  { label: "Services", href: "/admin/services", icon: LayersIcon },
  { label: "Testimonials", href: "/admin/testimonials", icon: MessageIcon },
  {
    label: "Profile",
    icon: CodeIcon,
    children: [
      { label: "Experience", href: "/admin/experience" },
      { label: "Education", href: "/admin/education" },
      { label: "Skills", href: "/admin/skills" },
    ],
  },
  { label: "Messages", href: "/admin/messages", icon: MessageIcon },
  { label: "Analytics", href: "/admin/analytics", icon: BarChartIcon },
  { label: "Settings", href: "/admin/settings", icon: SettingsIcon },
];

export default function AdminSidebar({
  unreadMessages = 0,
  onLogout,
  collapsed = false,
  onToggle,
}: {
  unreadMessages?: number;
  onLogout: () => void;
  collapsed?: boolean;
  onToggle?: () => void;
}) {
  const pathname = usePathname();
  const [expandedMenus, setExpandedMenus] = useState<string[]>(["Projects", "Profile"]);

  const toggleMenu = (label: string) => {
    setExpandedMenus((prev) =>
      prev.includes(label) ? prev.filter((l) => l !== label) : [...prev, label]
    );
  };

  const isActive = (href: string) => pathname === href;
  const isParentActive = (item: NavItem) =>
    item.children?.some((child) => pathname === child.href);

  return (
    <aside
      className={`fixed left-0 top-0 h-screen bg-surface-elevated border-r border-border flex flex-col transition-all duration-300 z-40 ${
        collapsed ? "w-20" : "w-64"
      }`}
    >
      {/* Logo */}
      <div className="h-16 flex items-center justify-between px-4 border-b border-border">
        <Link href="/admin/dashboard" className="flex items-center gap-3">
          <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-primary to-accent flex items-center justify-center shrink-0">
            <CodeIcon size={20} className="text-white" />
          </div>
          {!collapsed && (
            <div className="overflow-hidden">
              <h2 className="font-bold text-text-primary text-sm truncate">Samuel.dev</h2>
              <p className="text-[10px] text-text-muted">Admin Panel</p>
            </div>
          )}
        </Link>
        {onToggle && (
          <button
            onClick={onToggle}
            className="p-1.5 text-text-muted hover:text-text-primary rounded-lg hover:bg-white/5"
          >
            <ChevronDownIcon size={16} className={collapsed ? "rotate-[-90deg]" : "rotate-90"} />
          </button>
        )}
      </div>

      {/* Navigation */}
      <nav className="flex-1 overflow-y-auto p-3 space-y-1">
        {navigation.map((item) => {
          const Icon = item.icon;
          const hasChildren = !!item.children;
          const isExpanded = expandedMenus.includes(item.label);
          const active = item.href ? isActive(item.href) : isParentActive(item);

          if (hasChildren) {
            return (
              <div key={item.label}>
                <button
                  onClick={() => toggleMenu(item.label)}
                  className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm font-medium transition-all ${
                    active
                      ? "bg-primary/10 text-primary-light"
                      : "text-text-secondary hover:text-text-primary hover:bg-white/5"
                  }`}
                >
                  <Icon size={18} className="shrink-0" />
                  {!collapsed && (
                    <>
                      <span className="flex-1 text-left">{item.label}</span>
                      <ChevronDownIcon
                        size={14}
                        className={`transition-transform ${isExpanded ? "rotate-180" : ""}`}
                      />
                    </>
                  )}
                </button>
                {!collapsed && isExpanded && (
                  <div className="mt-1 ml-4 pl-4 border-l border-border space-y-1">
                    {item.children?.map((child) => (
                      <Link
                        key={child.href}
                        href={child.href}
                        className={`block px-3 py-2 rounded-lg text-sm transition-all ${
                          isActive(child.href)
                            ? "bg-primary/10 text-primary-light font-medium"
                            : "text-text-muted hover:text-text-primary hover:bg-white/5"
                        }`}
                      >
                        {child.label}
                      </Link>
                    ))}
                  </div>
                )}
              </div>
            );
          }

          return (
            <Link
              key={item.label}
              href={item.href!}
              className={`flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm font-medium transition-all ${
                active
                  ? "bg-primary/10 text-primary-light"
                  : "text-text-secondary hover:text-text-primary hover:bg-white/5"
              }`}
            >
              <Icon size={18} className="shrink-0" />
              {!collapsed && (
                <>
                  <span className="flex-1">{item.label}</span>
                  {item.label === "Messages" && unreadMessages > 0 && (
                    <span className="px-2 py-0.5 text-[10px] rounded-full bg-danger text-white">
                      {unreadMessages}
                    </span>
                  )}
                </>
              )}
            </Link>
          );
        })}
      </nav>

      {/* Bottom actions */}
      <div className="p-3 border-t border-border space-y-1">
        <Link
          href="/"
          target="_blank"
          className={`flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm font-medium text-text-secondary hover:text-text-primary hover:bg-white/5 transition-all ${
            collapsed ? "justify-center" : ""
          }`}
        >
          <HomeIcon size={18} />
          {!collapsed && <span>View Site</span>}
        </Link>
        <button
          onClick={onLogout}
          className={`w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm font-medium text-danger hover:bg-danger/10 transition-all ${
            collapsed ? "justify-center" : ""
          }`}
        >
          <LogOutIcon size={18} />
          {!collapsed && <span>Logout</span>}
        </button>
      </div>
    </aside>
  );
}
