import React, { useState, useMemo } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import { useGrStore } from '../services/useGrStore';
import {
  ChevronLeft,
  ChevronRight,
  Search,
  ChevronDown,
  Users,
  FileText,
  Settings,
  Lock,
  LogOut,
  Activity,
  LayoutDashboard,
  Mail,
  FileCheck,
  Truck,
  ClipboardCheck,
  Send,
  FolderOpen,
  FileSpreadsheet,
  ShieldCheck,
  Radio,
  MapPin
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { useAuthContext } from '@/components/shared/AuthProvider';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import './GrSidebar.css';

const MENU_ITEMS = [
  {
    id: 'op-geral',
    label: 'Visão Geral',
    path: '/plataforma/gr/operacoes/dashboard',
    icon: LayoutDashboard
  },
  {
    id: 'cadastros',
    label: 'Meus Cadastros',
    icon: Users,
    path: '/plataforma/gr/cadastros'
  },
  {
    id: 'contratos',
    label: 'Contratos',
    icon: FileText,
    path: '/plataforma/gr/contratos'
  },


  // {
  //   id: 'operacoes',
  //   label: 'Minhas Atividades',
  //   icon: Activity,
  //   path: '/plataforma/gr/operacoes',
  //   children: [
  //     // { id: 'op-monitoramento', label: 'Monitoramento', path: '/plataforma/gr/operacoes/monitoramento', icon: Radio },
  //     // { id: 'op-telemetria', label: 'Telemetria', path: '/plataforma/gr/operacoes/telemetria', icon: MapPin },
  //     // { id: 'op-outlook', label: 'Central de Mensagens', path: '/plataforma/gr/operacoes/outlook', icon: Mail },
  //     // { id: 'op-fiscal', label: 'Suporte Fiscal', path: '/plataforma/gr/operacoes/fiscal', icon: FileCheck },
  //     // { id: 'op-cte', label: 'Revisão de Cargas', path: '/plataforma/gr/operacoes/cte', icon: Truck },
  //     // { id: 'op-checklist', label: 'Saúde da Frota', path: '/plataforma/gr/operacoes/checklist', icon: ClipboardCheck },
  //     // { id: 'op-documentos', label: 'Meus Documentos', path: '/plataforma/gr/operacoes/documentos', icon: FolderOpen },
  //     // { id: 'op-planilhas', label: 'Controle Operacional', path: '/plataforma/gr/operacoes/planilhas', icon: FileSpreadsheet }
  //   ]
  // },
  {
    id: 'configuracoes',
    label: 'Minhas Configurações',
    icon: Settings,
    path: '/plataforma/gr/configuracoes'
  }
];

// 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 ? "gr-sublink" : "gr-link",
        isActive && !hasChildren && "active",
        isLocked && "gr-locked"
      )}
      onClick={() => {
        if (isLocked) return;
        if (hasChildren) toggleExpand(item.id);
      }}
      title={isLocked ? item.disabledReason : (isCollapsed ? item.label : '')}
    >
      <Icon size={isSub ? 16 : 20} className="gr-icon" />
      {(!isCollapsed || isSub) && <span className="gr-label">{item.label}</span>}

      {hasChildren && !isCollapsed && (
        <ChevronDown
          size={14}
          className={cn("gr-chevron", isExpanded && "expanded")}
        />
      )}

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

  return (
    <div className="gr-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="gr-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 GrSidebar = ({ 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 { userData } = useGrStore();
  const userGroup = userData?.usuario?.grupo || 'Despachante';

  const finalMenuItems = useMemo(() => {
    // Administrador has access to everything
    if (userGroup === 'Administrador') return filteredItems;

    // Despachante and Coordenador only have access to 'cadastros' and 'configuracoes'
    if (userGroup === 'Despachante' || userGroup === 'Documentação' || userGroup === 'Coordenador') {
      return filteredItems.filter(item => item.id === 'cadastros' || item.id === 'configuracoes');
    }

    return filteredItems;
  }, [filteredItems, userGroup]);


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

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

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

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

      <footer className="gr-footer">
        <div className="gr-brand">
          <div className="gr-brand-logo">
            GR
          </div>
          {!isCollapsed && (
            <div className="gr-brand-info">
              <span className="gr-brand-name">Cockpit <span>GR</span></span>
              <span className="gr-app-sub">Gestão de Risco</span>
            </div>
          )}
        </div>

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

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