'use client';

import * as React from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { 
  ChevronRight,
  MousePointer2, 
  Palette, 
  Eye, 
  Languages, 
  Layers,
  ChevronLeft,
  X
} from 'lucide-react';
import { cn } from '@/lib/utils/cn';
import Logo from '@/components/Logo';
import { useSidebar } from './SidebarProvider';
import { Button } from '@/components/ui/button';

interface NavItem {
  title: string;
  href: string;
  icon: React.ElementType | React.ReactNode;
  items?: { title: string; href: string }[];
}

interface NavGroup {
  label: string;
  items: NavItem[];
}

const PastelIcon = (props: any) => (
  <svg {...props} fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z" />
    <circle cx="6.5" cy="11.5" r="1" fill="currentColor" />
    <circle cx="9.5" cy="7.5" r="1" fill="currentColor" />
    <circle cx="14.5" cy="7.5" r="1" fill="currentColor" />
    <circle cx="17.5" cy="11.5" r="1" fill="currentColor" />
  </svg>
);

const UnitsIcon = (props: any) => (
  <svg {...props} fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 16V4m0 0L3 8m4-4l4 4m6 0v12m0 0l4-4m-4 4l-4-4" />
  </svg>
);

const FigletIcon = (props: any) => (
  <svg {...props} fill="none" stroke="currentColor" viewBox="0 0 24 24">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3.5 13h6" />
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="m2 16 4.5-9 4.5 9" />
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M18 16V7" />
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="m14 11 4-4 4 4" />
  </svg>
);

const navigation: NavGroup[] = [
  {
    label: 'Toolkit',
    items: [
      { 
        title: 'Units Converter', 
        href: '/units', 
        icon: <UnitsIcon className="h-4 w-4" /> 
      },
      { 
        title: 'Figlet ASCII', 
        href: '/figlet', 
        icon: <FigletIcon className="h-4 w-4" /> 
      },
      { 
        title: 'Pastel (Color)', 
        href: '/pastel', 
        icon: <PastelIcon className="h-4 w-4" />,
        items: [
          { title: 'Harmony Palettes', href: '/pastel/harmony' },
          { title: 'Distinct Colors', href: '/pastel/distinct' },
          { title: 'Gradients', href: '/pastel/gradient' },
          { title: 'Contrast Checker', href: '/pastel/contrast' },
          { title: 'Color Blindness', href: '/pastel/colorblind' },
          { title: 'Text Color', href: '/pastel/textcolor' },
          { title: 'Named Colors', href: '/pastel/names' },
          { title: 'Batch Operations', href: '/pastel/batch' },
        ]
      },
    ]
  }
];

export function AppSidebar() {
  const pathname = usePathname();
  const { isOpen, isCollapsed, close, toggleCollapse } = useSidebar();

  return (
    <>
      {/* Mobile Overlay Backdrop */}
      {isOpen && (
        <div 
          className="fixed inset-0 bg-background/80 backdrop-blur-sm z-40 lg:hidden"
          onClick={close}
        />
      )}

      <aside className={cn(
        "fixed inset-y-0 left-0 z-50 flex flex-col border-r border-border bg-background/40 backdrop-blur-2xl transition-all duration-300 ease-in-out lg:relative lg:h-full",
        isOpen ? "translate-x-0" : "-translate-x-full lg:translate-x-0",
        isCollapsed ? "lg:w-20" : "w-64"
      )}>
        {/* Sidebar Header */}
        <div className="flex h-16 items-center justify-between px-6 shrink-0 border-b border-border">
          <Link href="/" className="flex items-center gap-3 group overflow-hidden">
            <div className="shrink-0">
              <Logo size={isCollapsed ? 24 : 24} />
            </div>
            {!isCollapsed && (
              <span className="font-bold text-xl bg-clip-text text-transparent bg-gradient-to-r from-purple-400 to-pink-400 group-hover:opacity-80 transition-opacity whitespace-nowrap">
                Kit
              </span>
            )}
          </Link>
          <Button 
            variant="ghost" 
            size="icon" 
            className="lg:hidden text-muted-foreground"
            onClick={close}
          >
            <X className="h-5 w-5" />
          </Button>
        </div>

        {/* Navigation */}
        <nav className="flex-1 overflow-y-auto px-4 py-2 space-y-8 mt-4 scrollbar-hide">
          {navigation.map((group) => (
            <div key={group.label} className="space-y-2">
              {!isCollapsed && (
                <h4 className="px-3 text-xs font-semibold text-muted-foreground/50 uppercase tracking-wider">
                  {group.label}
                </h4>
              )}
              <div className="space-y-1">
                {group.items.map((item) => {
                  const isActive = pathname === item.href || (item.href !== '/' && pathname.startsWith(item.href));
                  
                  return (
                    <div key={item.href} className="space-y-1">
                      <Link
                        href={item.href}
                        onClick={() => { if (window.innerWidth < 1024) close(); }}
                        className={cn(
                          "flex items-center px-3 py-2 rounded-xl text-sm font-medium transition-all duration-300 relative group/item",
                          isActive
                            ? "bg-primary/10 text-primary shadow-[0_0_15px_rgba(139,92,246,0.15)] ring-1 ring-primary/20" 
                            : "text-muted-foreground hover:bg-accent/50 hover:text-foreground",
                          isCollapsed ? "justify-center" : "justify-between"
                        )}
                        title={isCollapsed ? item.title : undefined}
                      >
                        <div className="flex items-center gap-3">
                          <span className={cn(
                            "transition-colors duration-300 shrink-0",
                            isActive ? "text-primary" : "text-muted-foreground group-hover/item:text-foreground"
                          )}>
                            {React.isValidElement(item.icon) ? item.icon : null}
                          </span>
                          {!isCollapsed && <span className="whitespace-nowrap">{item.title}</span>}
                        </div>
                        
                        {!isCollapsed && item.items && (
                          <ChevronRight className={cn(
                            "h-3.5 w-3.5 transition-transform duration-300",
                            pathname.startsWith(item.href) && "rotate-90"
                          )} />
                        )}

                        {/* Collapsed Active Indicator */}
                        {isCollapsed && isActive && (
                          <div className="absolute left-0 w-1 h-6 bg-primary rounded-r-full" />
                        )}
                      </Link>
                      
                      {item.items && pathname.startsWith(item.href) && !isCollapsed && (
                        <div className="ml-9 space-y-1 border-l border-border pl-2 mt-1">
                          {item.items.map((subItem) => (
                            <Link
                              key={subItem.href}
                              href={subItem.href}
                              onClick={() => { if (window.innerWidth < 1024) close(); }}
                              className={cn(
                                "block px-3 py-1.5 rounded-lg text-xs font-medium transition-all duration-200",
                                pathname === subItem.href
                                  ? "text-primary bg-primary/5 font-semibold" 
                                  : "text-muted-foreground hover:text-foreground hover:bg-accent/50"
                              )}
                            >
                              {subItem.title}
                            </Link>
                          ))}
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            </div>
          ))}
        </nav>

        {/* Sidebar Footer / Desktop Toggle */}
        <div className="p-4 border-t border-border hidden lg:block">
          <Button
            variant="ghost"
            size="sm"
            className="w-full flex items-center justify-center gap-2 text-muted-foreground hover:text-foreground"
            onClick={toggleCollapse}
          >
            {isCollapsed ? (
              <ChevronRight className="h-4 w-4" />
            ) : (
              <>
                <ChevronLeft className="h-4 w-4" />
                <span className="text-xs font-semibold uppercase tracking-wider">Collapse Sidebar</span>
              </>
            )}
          </Button>
        </div>
      </aside>
    </>
  );
}
