import React, { useState, useMemo } from 'react';
import { useLocation } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import { 
  ChevronLeft, 
  ChevronRight, 
  Search, 
  ChevronDown, 
  LayoutDashboard,
  ArrowUpRight,
  ArrowDownRight,
  ArrowRightLeft,
  Settings,
  ShieldCheck,
  Zap,
  Lock,
  LogOut
} from 'lucide-react';
import { cn } from '@/lib/utils';
import logo from '@/assets/Img/Util/iT_Guys/logo1.png';

// Reusando os estilos do Sidebar original (Reproduced)
import '@/features/layout/components/Sidebar/Sidebar.css';

const MENU_ITEMS = [
  {
    id: 'dashboard',
    label: 'Dashboard',
    icon: LayoutDashboard,
    category: 'Geral'
  },
  {
    id: 'financeiro',
    label: 'Financeiro',
    icon: ShieldCheck,
    category: 'Financeiro',
    children: [
      { id: 'entradas', label: 'Receitas (Entradas)', icon: ArrowUpRight, pathId: 'entradas' },
      { id: 'saidas', label: 'Despesas (Saídas)', icon: ArrowDownRight, pathId: 'saidas' },
      { id: 'conciliacao', label: 'Conciliação Bancária', icon: ArrowRightLeft, pathId: 'conciliacao' }
    ]
  },
  {
    id: 'configuracoes',
    label: 'Ajustes',
    icon: Settings,
    category: 'Sistema',
    pathId: 'config'
  }
];

/**
 * WorkspaceSidebar - Versão "Reproduced" com alta fidelidade visual (Angular Style)
 * Implementa a logo oficial iTGUYS e acentos em Ouro (#f1c232).
 */
export const WorkspaceSidebar = ({ activeScreen, onScreenChange }) => {
  const [isCollapsed, setIsCollapsed] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [expandedItems, setExpandedItems] = useState({ 'financeiro': true });

  const toggleSidebar = () => setIsCollapsed(!isCollapsed);

  const toggleExpand = (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 MenuItem = ({ item, isSub = false }) => {
    const Icon = item.icon;
    const hasChildren = item.children && item.children.length > 0;
    const isExpanded = expandedItems[item.id];
    
    // Identificar se está ativo
    const isActive = activeScreen === (item.pathId || item.id) || 
                     (hasChildren && item.children.some(c => activeScreen === (c.pathId || c.id)));

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

    return (
      <div className="sb-item">
        {content}

        {hasChildren && isExpanded && !isCollapsed && (
          <motion.div 
            initial={{ opacity: 0, height: 0 }}
            animate={{ opacity: 1, height: 'auto' }}
            exit={{ opacity: 0, height: 0 }}
            className="sb-submenu"
          >
            {item.children.map(child => (
              <MenuItem key={child.id} item={child} isSub />
            ))}
          </motion.div>
        )}
      </div>
    );
  };

  return (
    <aside 
      className={cn("sb-container relative h-full top-auto left-auto border-none rounded-none bg-white dark:bg-[var(--workspace-sec-5-dark)]", isCollapsed && "collapsed")}
      style={{ boxShadow: '10px 0 30px rgba(0,0,0,0.5)' }}
    >
      {/* Subtle Top Glow (Angular Style) */}
      <div className="absolute top-0 left-0 right-0 h-[2px] bg-gradient-to-r from-transparent via-[#f1c232] to-transparent opacity-40" />

      {/* Header com Toggle */}
      <div className="sb-toggle-container">
        <button className="sb-toggle-btn bg-slate-100 dark:bg-zinc-800 border-slate-200 dark:border-zinc-700" onClick={toggleSidebar}>
          {isCollapsed ? <ChevronRight size={18} /> : <ChevronLeft size={18} />}
        </button>
      </div>

      {/* Logo Area */}
      <div className={cn("px-6 mb-8 mt-2 transition-all", isCollapsed ? "flex justify-center" : "")}>
        {!isCollapsed ? (
          <div className="flex flex-col items-center">
             <img src={logo} alt="iTGUYS" className="h-12 w-auto mb-2 drop-shadow-[0_0_15px_rgba(241,194,50,0.2)]" />
             <div className="h-[1px] w-12 bg-[#f1c232]/30 mt-1" />
             <span className="text-[10px] uppercase font-black tracking-[0.4em] text-[#f1c232]/40 mt-2 italic">Workspace</span>
          </div>
        ) : (
          <div className="w-10 h-10 bg-[#f1c232] rounded-xl flex items-center justify-center shadow-lg shadow-[#f1c232]/20">
             <Zap size={22} className="text-[#1a1a1a] fill-[#1a1a1a]" />
          </div>
        )}
      </div>

      {/* Search */}
      <div className="sb-search-wrapper">
        <div className="relative">
          <input 
            type="text" 
            className="sb-search-input bg-slate-50 dark:bg-white/[0.05] border-slate-200 dark:border-white/10" 
            placeholder="Buscar..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />
          <Search size={14} className="absolute right-4 top-1/2 -translate-y-1/2 text-slate-400 dark:text-zinc-600" />
        </div>
      </div>

      {/* Menu scrollable */}
      <nav className="sb-menu-content custom-scrollbar">
        {filteredItems.map(item => (
          <MenuItem key={item.id} item={item} />
        ))}
      </nav>

      {/* Footer / User Profile */}
      <footer className="sb-footer border-t border-slate-100 dark:border-white/5 bg-slate-50 dark:bg-zinc-900/50">
        <div className={cn("sb-brand", isCollapsed && "justify-center mb-0")}>
          <div className="sb-brand-logo bg-[#f1c232]">
            <Zap size={20} className="text-[#1a1a1a]" />
          </div>
          {!isCollapsed && (
            <div className="sb-brand-info">
              <span className="sb-brand-name" style={{ color: '#f1c232' }}>iTGUYS</span>
              <span className="sb-app-name text-slate-400 dark:text-zinc-500">Master Core v4</span>
            </div>
          )}
        </div>

        {!isCollapsed && (
          <div className="sb-legal border-slate-200 dark:border-zinc-800">
            <div className="sb-legal-item">
               <ShieldCheck size={12} className="text-[#f1c232]" />
               <span className="text-slate-400 dark:text-zinc-600 font-bold uppercase tracking-tighter">Conexão Segura</span>
            </div>
          </div>
        )}

        <div className={cn("sb-version text-slate-300 dark:text-zinc-700", isCollapsed && "justify-center")}>
           <Lock size={12} className="text-slate-300 dark:text-zinc-800" />
           {!isCollapsed && <span>Licença Corporativa</span>}
        </div>
      </footer>
    </aside>
  );
};
