'use client';

import { ReactNode, useState } from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { cn } from '../../lib/utils';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import { Button } from '../ui/button';

export interface SidebarLink {
  href: string;
  label: string;
  icon?: ReactNode;
}

export interface SidebarSection {
  title?: string;
  links: SidebarLink[];
}

export interface SidebarProps {
  /**
   * Application name/logo
   */
  appName: string;
  /**
   * Navigation sections
   */
  sections: SidebarSection[];
  /**
   * User dropdown content (rendered at bottom of sidebar)
   */
  userDropdown?: ReactNode;
  /**
   * Additional className for sidebar
   */
  className?: string;
  /**
   * Whether sidebar is collapsible
   */
  collapsible?: boolean;
  /**
   * Default collapsed state (uncontrolled)
   */
  defaultCollapsed?: boolean;
  /**
   * Controlled collapsed state. Pass with onCollapsedChange when the surrounding
   * layout also needs to know (see AppShell — the content spacer must shrink with
   * the rail, otherwise "Collapse" only narrows the rail and leaves a dead gap).
   */
  collapsed?: boolean;
  /** Fires whenever the collapse toggle is used. */
  onCollapsedChange?: (collapsed: boolean) => void;
}

export function Sidebar({
  appName,
  sections,
  userDropdown,
  className,
  collapsible = true,
  defaultCollapsed = false,
  collapsed: controlledCollapsed,
  onCollapsedChange,
}: SidebarProps) {
  const pathname = usePathname();
  const [internalCollapsed, setInternalCollapsed] = useState(defaultCollapsed);
  const collapsed = controlledCollapsed ?? internalCollapsed;
  const setCollapsed = (next: boolean) => {
    if (controlledCollapsed === undefined) setInternalCollapsed(next);
    onCollapsedChange?.(next);
  };

  const isActivePath = (href: string) => {
    if (href === '/') {
      return pathname === '/';
    }
    return pathname.startsWith(href);
  };

  return (
    <div
      className={cn(
        'fixed left-0 inset-y-0 z-30 flex flex-col bg-gray-900 text-white transition-all duration-200',
        collapsed ? 'w-20' : 'w-64',
        className
      )}
    >
      {/* Logo */}
      <div className="p-4 border-b border-gray-800">
        <Link
          href="/"
          className={cn(
            'font-bold transition-colors hover:text-primary',
            collapsed ? 'text-lg' : 'text-xl'
          )}
        >
          {collapsed ? appName.substring(0, 2).toUpperCase() : appName}
        </Link>
      </div>

      {/* Navigation */}
      <nav className="flex-1 overflow-y-auto p-4 space-y-6">
        {sections.map((section, idx) => (
          <div key={idx}>
            {section.title && !collapsed && (
              <h3 className="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-2 px-3">
                {section.title}
              </h3>
            )}
            <div className="space-y-1">
              {section.links.map((link) => {
                const isActive = isActivePath(link.href);
                return (
                  <Link
                    key={link.href}
                    href={link.href}
                    className={cn(
                      'flex items-center gap-3 px-3 py-2 rounded-md text-sm font-medium transition-colors',
                      isActive
                        ? 'bg-primary text-primary-foreground shadow-sm'
                        : 'text-gray-300 hover:bg-gray-800 hover:text-white',
                      collapsed && 'justify-center'
                    )}
                  >
                    {link.icon ? (
                      <span className="flex-shrink-0 w-5 h-5">
                        {link.icon}
                      </span>
                    ) : null}
                    {!collapsed && <span>{link.label}</span>}
                  </Link>
                );
              })}
            </div>
          </div>
        ))}
      </nav>

      {/* User Dropdown */}
      {userDropdown && (
        <div className="p-4 border-t border-gray-800">
          {userDropdown}
        </div>
      )}

      {/* Collapse Toggle */}
      {collapsible && (
        <div className={cn('p-4 border-t border-gray-800', userDropdown && 'border-t-0')}>
          <Button
            variant="ghost"
            size="sm"
            onClick={() => setCollapsed(!collapsed)}
            className="w-full text-gray-400 hover:text-white hover:bg-gray-800"
          >
            {collapsed ? (
              <ChevronRight className="w-5 h-5" />
            ) : (
              <>
                <ChevronLeft className="w-5 h-5 mr-2" />
                <span>Collapse</span>
              </>
            )}
          </Button>
        </div>
      )}
    </div>
  );
}

/**
 * Layout wrapper that adds proper spacing for sidebar
 */
export interface SidebarLayoutProps {
  children: ReactNode;
  collapsed?: boolean;
}

export function SidebarLayout({ children, collapsed = false }: SidebarLayoutProps) {
  return (
    <div className="flex h-screen bg-background">
      {/* Spacer for fixed sidebar */}
      <div className={cn('flex-shrink-0 transition-all duration-200', collapsed ? 'w-20' : 'w-64')} />

      {/* Main content area */}
      <div className="flex-1 overflow-auto">
        <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6 sm:py-8">
          {children}
        </main>
      </div>
    </div>
  );
}
