import React, { useState, useMemo } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import { 
  ChevronLeft, 
  ChevronRight, 
  Search, 
  ChevronDown, 
  LayoutDashboard,
  Car,
  Users,
  Wrench,
  Activity,
  Radio,
  AlertTriangle,
  Store,
  ClipboardList,
  LogOut,
  ShieldAlert,
  Building2,
  Award,
  GitBranch,
  Lock
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { useAuthContext } from '@/components/shared/AuthProvider';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import './PrafrotSidebar.css';

const MENU_ITEMS = [
  {
    id: 'dashboard',
    label: 'Estatísticas',
    icon: LayoutDashboard,
    path: '/plataforma/prafrot/estatisticas'
  },
  {
    id: 'cadastros',
    label: 'Cadastros',
    icon: ClipboardList,
    children: [
      { id: 'c-veiculos', label: 'Veículos', path: '/plataforma/prafrot/veiculos', icon: Car },
      { id: 'c-dispatcher', label: 'Dispatcher', path: '/plataforma/prafrot/dispatcher', icon: ClipboardList },
      // { id: 'c-motoristas', label: 'Motoristas', path: '/plataforma/prafrot/motoristas', icon: Users, disabled: true, disabledReason: 'Funcionalidade em manutenção' },
      { id: 'c-oficinas', label: 'Oficinas', path: '/plataforma/prafrot/oficinas', icon: Store }
    ]
  },
  {
    id: 'gerencia',
    label: 'Gerência',
    icon: Activity,
    children: [
      { id: 'g-monitoramento', label: 'Monitoramento', path: '/plataforma/prafrot/monitoramento', icon: Radio },
      { id: 'g-manutencao', label: 'Manutenção', path: '/plataforma/prafrot/manutencao', icon: Wrench },
      { id: 'g-sinistros', label: 'Sinistros', path: '/plataforma/prafrot/sinistros', icon: AlertTriangle }
    ]
  }
];

// Optimized MenuItem component outside main render loop
const MenuItem = React.memo(({ item, isSub = false, isCollapsed, expandedItems, toggleExpand, pathname, searchTerm }) => {
  const Icon = item.icon;
  const hasChildren = item.children && item.children.length > 0;
  const isExpanded = expandedItems[item.id];
  const isActive = pathname.startsWith(item.path) || (hasChildren && item.children.some(c => pathname.startsWith(c.path)));
  const isLocked = item.disabled;

  // Filter sub-items if searching
  const subItems = item.children?.filter(child => 
    !searchTerm || child.label.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const content = (
    <div 
      className={cn(
        isSub ? "pfs-sublink" : "pfs-link",
        isActive && !hasChildren && "active",
        isLocked && "pfs-locked"
      )}
      onClick={() => {
        if (isLocked) return;
        if (hasChildren) toggleExpand(item.id);
      }}
      title={isLocked ? item.disabledReason : (isCollapsed ? item.label : '')}
    >
      <Icon size={isSub ? 16 : 20} className="pfs-icon" />
      {(!isCollapsed || isSub) && <span className="pfs-label">{item.label}</span>}
      
      {hasChildren && !isCollapsed && (
        <ChevronDown 
          size={14} 
          className={cn("pfs-chevron", isExpanded && "expanded")} 
        />
      )}

      {isLocked && !isCollapsed && (
        <Lock size={12} className="pfs-lock-icon" />
      )}
    </div>
  );

  return (
    <div className="pfs-item-wrapper">
      {item.path && !hasChildren && !isLocked ? (
        <Link to={item.path} style={{ textDecoration: 'none' }}>
          {content}
        </Link>
      ) : content}

      <AnimatePresence>
        {hasChildren && isExpanded && !isCollapsed && (
          <motion.div 
            initial={{ opacity: 0, height: 0 }}
            animate={{ opacity: 1, height: 'auto' }}
            exit={{ opacity: 0, height: 0 }}
            className="pfs-submenu"
          >
            {subItems?.map(child => (
              <MenuItem 
                key={child.id} 
                item={child} 
                isSub 
                isCollapsed={isCollapsed}
                expandedItems={expandedItems}
                toggleExpand={toggleExpand}
                pathname={pathname}
                searchTerm={searchTerm}
              />
            ))}
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
});

MenuItem.displayName = 'MenuItem';

export const PrafrotSidebar = ({ isCollapsed, onToggle }) => {
  const [searchTerm, setSearchTerm] = useState('');
  const [expandedItems, setExpandedItems] = useState({ cadastros: true, gerencia: true });
  const location = useLocation();
  const { user, logout } = useAuthContext();

  const toggleExpand = React.useCallback((id) => {
    setExpandedItems(prev => ({
      ...prev,
      [id]: !prev[id]
    }));
  }, []);

  const filteredItems = useMemo(() => {
    if (!searchTerm) return MENU_ITEMS;
    
    return MENU_ITEMS.filter(item => {
      const matchParent = item.label.toLowerCase().includes(searchTerm.toLowerCase());
      const matchChildren = item.children?.some(child => 
        child.label.toLowerCase().includes(searchTerm.toLowerCase())
      );
      return matchParent || matchChildren;
    });
  }, [searchTerm]);

  const handleLogout = () => {
    logout();
    window.location.href = '/plataforma/prafrot/login';
  };

  return (
    <aside className={cn("pfs-container", isCollapsed && "collapsed")}>
      <div className="pfs-toggle-container">
        <button className="pfs-toggle-btn" onClick={onToggle}>
          {isCollapsed ? <ChevronRight size={18} /> : <ChevronLeft size={18} />}
        </button>
      </div>

      <div className="pfs-search-wrapper">
        <div className="relative">
          <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-[var(--pfs-text-muted)]" />
          <input 
            type="text" 
            className="pfs-search-input" 
            placeholder="Buscar..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />
        </div>
      </div>

      <nav className="pfs-nav-content custom-scrollbar">
        {filteredItems.map(item => (
          <MenuItem 
            key={item.id} 
            item={item} 
            isCollapsed={isCollapsed}
            expandedItems={expandedItems}
            toggleExpand={toggleExpand}
            pathname={location.pathname}
            searchTerm={searchTerm}
          />
        ))}
      </nav>

      <footer className="pfs-footer">
        <div className="pfs-brand">
          <div className="pfs-brand-logo">
            PF
          </div>
          {!isCollapsed && (
            <div className="pfs-brand-info">
              <span className="pfs-brand-name">PRA<span>FROTA</span></span>
              <span className="pfs-app-sub">Fleet Management</span>
            </div>
          )}
        </div>

        <div className="pfs-user-section">
          <div className={cn("pfs-user-card", isCollapsed && "justify-center")}>
            <Avatar className="h-8 w-8 border border-[var(--pfs-border)]">
              <AvatarImage src={`https://ui-avatars.com/api/?name=${user?.name || 'User'}&background=10b981&color=141414`} />
              <AvatarFallback className="bg-emerald-500 text-zinc-950 font-bold text-xs">
                {(user?.name || 'U').charAt(0)}
              </AvatarFallback>
            </Avatar>
            {!isCollapsed && (
              <div className="pfs-user-data">
                <span className="pfs-user-name">{user?.name || 'Usuário'}</span>
                <button onClick={handleLogout} className="pfs-logout-link">
                  <LogOut size={10} /> Sair
                </button>
              </div>
            )}
          </div>
        </div>

      </footer>
    </aside>
  );
};
