import { useState } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { motion } from 'framer-motion';
import { ChevronRight, LayoutDashboard, Database, ClipboardList, ShieldCheck, Settings, Users, Box, ThermometerSun, Sprout } from 'lucide-react';
import { usePermissions } from '../../hooks/usePermissions';
import { getFilteredNavSections, type NavSection as NavSectionType, type NavItem } from '../../lib/navigation';
import { cn } from '../../lib/utils';

interface SidebarProps {
    onItemClick?: () => void;
}

/**
 * Desktop sidebar navigation
 * Operations Command Center style: High contrast, authoritative, cultivation-focused
 */
export function Sidebar({ onItemClick }: SidebarProps) {
    const { role } = usePermissions();
    const sections = getFilteredNavSections(role);
    const location = useLocation();

    return (
        <nav className="flex-1 px-4 space-y-6 overflow-y-auto custom-scrollbar pb-8">
            {sections.map(section => (
                <NavSection
                    key={section.id}
                    section={section}
                    currentPath={location.pathname}
                    onItemClick={onItemClick}
                />
            ))}
        </nav>
    );
}

interface NavSectionProps {
    section: NavSectionType;
    currentPath: string;
    onItemClick?: () => void;
    defaultOpen?: boolean;
}

function NavSection({ section, currentPath, onItemClick, defaultOpen }: NavSectionProps) {
    const hasActiveItem = section.items.some(item => item.path === currentPath);
    const [isOpen, setIsOpen] = useState(hasActiveItem || defaultOpen !== false);

    return (
        <div className="space-y-1">
            {/* Section Header */}
            <button
                onClick={() => setIsOpen(!isOpen)}
                className="w-full flex items-center justify-between px-2 py-1 text-[10px] font-bold text-[var(--color-text-tertiary)] uppercase tracking-[0.2em] hover:text-slate-900 dark:hover:text-slate-100 transition-colors duration-fast group"
            >
                <span>{section.label}</span>
                <ChevronRight
                    size={10}
                    className={cn(
                        "transition-transform duration-300 opacity-0 group-hover:opacity-100",
                        isOpen ? 'rotate-90' : ''
                    )}
                />
            </button>

            {/* Section Items */}
            <div
                className={cn(
                    "space-y-0.5 transition-all duration-300 ease-in-out overflow-hidden",
                    isOpen ? 'opacity-100 mt-2' : 'max-h-0 opacity-0'
                )}
            >
                {section.items.map(item => (
                    <NavItemLink
                        key={item.id}
                        item={item}
                        isActive={currentPath === item.path}
                        onClick={onItemClick}
                    />
                ))}
            </div>
        </div>
    );
}

interface NavItemLinkProps {
    item: NavItem;
    isActive: boolean;
    onClick?: () => void;
}

function NavItemLink({ item, isActive, onClick }: NavItemLinkProps) {
    const Icon = item.icon;

    return (
        <Link
            to={item.path}
            onClick={onClick}
            className={cn(
                "group flex items-center gap-3 px-3 py-2 rounded-lg transition-all duration-200 relative",
                isActive
                    ? "bg-[var(--color-primary)]/10 text-[var(--color-primary)] dark:text-emerald-400 font-semibold"
                    : "text-slate-600 dark:text-[var(--color-text-tertiary)] hover:bg-slate-100 dark:hover:bg-slate-900 hover:text-slate-900 dark:hover:text-slate-200"
            )}
            aria-current={isActive ? 'page' : undefined}
        >
            <div className={cn(
                "p-1.5 rounded-md transition-all duration-300",
                isActive
                    ? "bg-[var(--color-primary)] text-white shadow-lg shadow-emerald-500/30"
                    : "bg-[var(--color-bg-tertiary)] text-[var(--color-text-tertiary)] group-hover:bg-slate-200 dark:group-hover:bg-slate-800"
            )}>
                <Icon
                    size={14}
                    strokeWidth={isActive ? 2.5 : 2}
                />
            </div>

            <span className="truncate text-[13px] tracking-tight">{item.label}</span>

            {/* Subtle Active Indicator Bar */}
            {isActive && (
                <motion.div
                    layoutId="sidebar-active"
                    className="absolute left-0 w-1 h-6 bg-[var(--color-primary)] rounded-r-full"
                    transition={{ type: "spring", stiffness: 300, damping: 30 }}
                />
            )}
        </Link>
    );
}
