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,
  Users,
  Briefcase,
  LogOut,
  Lock,
  UserCheck,
  Sun,
  Moon,
  FileCheck,
  Gift,
  ClipboardList,
  UserCog,
  Calendar
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { useAuthContext } from '@/components/shared/AuthProvider';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import './RhSidebar.css';

const MENU_ITEMS = [
  {
    id: 'dashboard',
    label: 'Dashboard',
    icon: LayoutDashboard,
    path: '/plataforma/rh/dashboard'
  },
  // {
  //   id: 'trabalhadores',
  //   label: 'Trabalhadores',
  //   icon: UserCog,
  //   path: '/plataforma/rh/trabalhadores'
  // },
  {
    id: 'colaboradores',
    label: 'Colaboradores',
    icon: Users,
    path: '/plataforma/rh/colaboradores'
  },
  {
    id: 'departamento-pessoal',
    label: 'Departamento Pessoal',
    icon: Briefcase,
    children: [
      // { id: 'faltas-atestados', label: 'Faltas e Atestados', path: '/plataforma/rh/faltas-atestados', icon: ClipboardList },
      { id: 'aniversariantes', label: 'Aniversariantes', path: '/plataforma/rh/aniversariantes', icon: Gift },
      { id: 'contratos-experiencia', label: 'Contratos de Experiência', path: '/plataforma/rh/contratos-experiencia', icon: FileCheck },
      { id: 'gestao-ferias', label: 'Gestão de Férias', path: '/plataforma/rh/gestao-ferias', icon: Calendar },
      // { id: 'ponto', label: 'Ponto Eletrônico', path: '/plataforma/rh/ponto', icon: UserCheck },
    ]
  }
];

// Optimized MenuItem component
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;

  const subItems = item.children?.filter(child => 
    !searchTerm || child.label.toLowerCase().includes(searchTerm.toLowerCase())
  );

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

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

  return (
    <div className="rhs-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="rhs-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 RhSidebar = ({ isCollapsed, onToggle, theme, onThemeToggle }) => {
  const [searchTerm, setSearchTerm] = useState('');
  const [expandedItems, setExpandedItems] = useState({ 'departamento-pessoal': 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('rh');
    window.location.href = '/plataforma/rh/login';
  };

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

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

      <nav className="rhs-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="rhs-footer">
        <div className="rhs-brand">
          <div className="rhs-brand-logo">
            <Briefcase size={22} className="text-[#141414]" />
          </div>
          {!isCollapsed && (
            <div className="rhs-brand-info">
              <span className="rhs-brand-name">Pra<span>Gente</span></span>
              <span className="rhs-app-sub">Gestão de Pessoas</span>
            </div>
          )}
        </div>

        <div className="rhs-user-section">
          <div className={cn("rhs-user-card", isCollapsed && "justify-center")}>
            <Avatar className="h-8 w-8 border border-[var(--rhs-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-semibold text-[clamp(1rem,1.2vw,1.125rem)]">
                {(user?.name || 'U').charAt(0)}
              </AvatarFallback>
            </Avatar>
            {!isCollapsed && (
              <div className="rhs-user-data">
                <span className="rhs-user-name">{user?.name || 'Usuário'}</span>
                <button onClick={handleLogout} className="rhs-logout-link">
                  <LogOut size={10} /> Sair
                </button>
              </div>
            )}
          </div>
        </div>

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