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,
  Wallet,
  Settings,
  ShieldCheck,
  Zap,
  Lock,
  LogOut
} from 'lucide-react';
import { cn } from '@/lib/utils';
import logo from '@/assets/Img/Util/iT_Guys/logo_2.png';

import '@/features/workspace/components/WorkspaceSidebar.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: 'fluxo-de-caixa', label: 'Fluxo de Caixa', icon: Wallet, pathId: 'fluxo-de-caixa' },
      { id: 'conciliacao', label: 'Conciliação Bancária', icon: ArrowRightLeft, pathId: 'conciliacao' }
    ]
  },
  {
    id: 'configuracoes',
    label: 'Ajustes',
    icon: Settings,
    category: 'Sistema',
    pathId: 'config'
  }
];

export const WorkspaceSidebar = ({ activeScreen, onScreenChange, isCollapsed, onToggle }) => {
  const [searchTerm, setSearchTerm] = useState('');
  const [expandedItems, setExpandedItems] = useState({ 'financeiro': true });

  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];
    
    const isActive = activeScreen === (item.pathId || item.id) || 
                     (hasChildren && item.children.some(c => activeScreen === (c.pathId || c.id)));

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

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

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

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

      <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-10 w-auto mb-2 drop-shadow-[0_0_15px_rgba(38,177,199,0.2)]" />
             <div className="h-[1px] w-12 bg-[#26b1c7]/30 mt-1" />
             <span className="text-[10px] uppercase font-bold tracking-[0.4em] text-[#26b1c7]/40 mt-2">Workspace</span>
          </div>
        ) : (
          <div className="w-10 h-10 flex items-center justify-center">
             <img src={logo} alt="iTGUYS" className="h-6 w-auto" />
          </div>
        )}
      </div>

      <div className="ws-search-wrapper">
        <div className="relative">
          <input 
            type="text" 
            className="ws-search-input" 
            placeholder="Buscar..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />
          <Search size={14} className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 dark:text-zinc-600" />
        </div>
      </div>

      <nav className="ws-nav-content custom-scrollbar">
        {filteredItems.map(item => (
          <MenuItem key={item.id} item={item} />
        ))}
      </nav>

      <footer className="ws-footer">
        <div className={cn("ws-brand", isCollapsed && "justify-center mb-0")}>
          {/* <div className="ws-brand-logo">
            <Zap size={20} />
          </div> */}
             <img src={logo} alt="iTGUYS" className="h-10 w-auto mb-2 drop-shadow-[0_0_15px_rgba(38,177,199,0.2)]" />

          {!isCollapsed && (
            <div className="ws-brand-info">
               <span className="ws-brand-name">iT<span>GUYS</span></span>
               {/* <span className="ws-app-sub">Master Core v4</span> */}
            </div>
          )}
        </div>
      </footer>
    </aside>
  );
};
