import React, { useState, useMemo } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { 
  ChevronLeft, 
  ChevronRight, 
  Search, 
  LayoutDashboard,
  Users,
  FileText,
  FolderTree,
  LogOut,
  Receipt,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { useAuthContext } from '@/components/shared/AuthProvider';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import './CnabSidebar.css';

const MENU_ITEMS = [
  {
    id: 'dashboard',
    label: 'Dashboard',
    icon: LayoutDashboard,
    path: '/plataforma/financeiro-cnab/dashboard'
  },
  {
    id: 'transacoes',
    label: 'Relatórios',
    icon: Receipt,
    path: '/plataforma/financeiro-cnab/transacoes'
  },
  {
    id: 'favorecidos',
    label: 'Favorecidos',
    icon: Users,
    path: '/plataforma/financeiro-cnab/favorecidos'
  },
  {
    id: 'gerar-remessa',
    label: 'Gerar Remessa',
    icon: FileText,
    path: '/plataforma/financeiro-cnab/gerar-remessa'
  },
  {
    id: 'gerenciar-pastas',
    label: 'Gerenciar Pastas',
    icon: FolderTree,
    path: '/plataforma/financeiro-cnab/gerenciar-pastas'
  }
];

const MenuItem = React.memo(({ item, isCollapsed, pathname, searchTerm }) => {
  const Icon = item.icon;
  const isActive = pathname.startsWith(item.path);

  return (
    <div className="pfs-item-wrapper">
      <Link to={item.path} style={{ textDecoration: 'none' }}>
        <div 
          className={cn(
            "pfs-link",
            isActive && "active"
          )}
          title={isCollapsed ? item.label : ''}
        >
          <Icon size={20} className="pfs-icon" />
          {!isCollapsed && <span className="pfs-label">{item.label}</span>}
        </div>
      </Link>
    </div>
  );
});

MenuItem.displayName = 'MenuItem';

export const CnabSidebar = ({ isCollapsed, onToggle }) => {
  const [searchTerm, setSearchTerm] = useState('');
  const location = useLocation();
  const { user, logout } = useAuthContext();

  const filteredItems = useMemo(() => {
    if (!searchTerm) return MENU_ITEMS;
    return MENU_ITEMS.filter(item => 
      item.label.toLowerCase().includes(searchTerm.toLowerCase())
    );
  }, [searchTerm]);

  const handleLogout = () => {
    logout('financeiro');
    window.location.href = '/plataforma/auth/login-cnab';
  };

  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}
            pathname={location.pathname}
            searchTerm={searchTerm}
          />
        ))}
      </nav>

      <footer className="pfs-footer">
        <div className="pfs-brand">
          <div className="pfs-brand-logo">
            CN
          </div>
          {!isCollapsed && (
            <div className="pfs-brand-info">
              <span className="pfs-brand-name">CNAB<span>240</span></span>
              <span className="pfs-app-sub">Central Financeira</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>
  );
};
