import React, { useState, useEffect } from 'react';
import { 
  Bell,
  Search,
  Maximize2,
  User,
  Zap,
  LayoutDashboard,
  Sun,
  Moon,
  Settings,
  LogOut
} from 'lucide-react';
import { Toaster } from 'sonner';
import { cn } from '@/lib/utils';
import { useDocumentMetadata } from '@/hooks/useDocumentMetadata';
import { useAuthContext } from '@/components/shared/AuthProvider';
import { WorkspaceSidebar } from './WorkspaceSidebar';
import { ContasReceberView } from '../../financeiro-v2/views/contas-receber/ContasReceberView';
import { ContasPagarView } from '../../financeiro-v2/views/contas-pagar/ContasPagarView';
import { ConciliacaoView } from '../../financeiro-v2/views/conciliacao-v2/ConciliacaoView';
import { DashboardView } from '../../financeiro-v2/views/DashboardView';
import { FluxoCaixaView } from '../../financeiro-v2/views/FluxoCaixaView';
import logo from '@/assets/Img/Util/iT_Guys/Logo 32x32.png';
import { clearModuleToken, clearUserForModule } from '@/utils/tokenManager';

/**
 * WorkspaceLayout - O container principal para o ambiente de teste/workspace.
 * Refinado com o design "Reproduced" e a identidade visual oficial da iTGUYS.
 */
/**
 * WorkspaceLayout - O container principal para o ambiente de teste/workspace.
 * Refinado com o design paritário ao "Prafrota", utilizando a paleta azul e alta fidelidade visual.
 * 
 * @returns {JSX.Element}
 */
const WORKSPACE_ENV_NAME = 'Workspace';
const WORKSPACE_BRAND_NAME = 'iTGUYS';

export const WorkspaceLayout = () => {
  const [activeScreen, setActiveScreen] = useState('entradas');
  const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(false);
  const [isDarkMode, setIsDarkMode] = useState(true);
  const { logout } = useAuthContext();

  useDocumentMetadata(`${WORKSPACE_ENV_NAME} | ${WORKSPACE_BRAND_NAME}`, 'workspace');

  useEffect(() => {
    if (isDarkMode) {
      document.documentElement.classList.add('dark');
    } else {
      document.documentElement.classList.remove('dark');
    }
  }, [isDarkMode]);

  // Mapeamento de nomes de tela amigáveis
  const screenNames = {
    dashboard: 'Dashboard',
    entradas: 'Receitas',
    saidas: 'Despesas',
    'fluxo-de-caixa': 'Fluxo de Caixa',
    conciliacao: 'Conciliação',
    config: 'Ajustes'
  };

  const handleLogout = async () => {
    // SEGURANÇA: Limpa Apenas o Workspace
    await logout('workspace');

    // Redireciona explicitamente para a tela de login do Workspace
    window.location.href = '/plataforma/workspace/login';
  };

  const handleDashboardNavigate = (route) => {
    const routeMap = {
      'receber': 'entradas',
      'contas-receber': 'entradas',
      'contas-receber/novo': 'entradas',
      'pagar': 'saidas',
      'contas-pagar': 'saidas',
      'conciliacao': 'conciliacao'
    };
    
    const target = routeMap[route] || route;
    if (Object.keys(screenNames).includes(target)) {
        setActiveScreen(target);
    }
  };

  const renderScreen = () => {
    switch (activeScreen) {
      case 'dashboard':
        return <DashboardView onNavigate={handleDashboardNavigate} />;
      case 'entradas':
        return <ContasReceberView />;
      case 'saidas':
        return <ContasPagarView />;
      case 'fluxo-de-caixa':
        return <FluxoCaixaView />;
      case 'conciliacao':
        return <ConciliacaoView />;
      case 'config':
        return (
          <div className="flex flex-col items-center justify-center min-h-[500px] text-zinc-400">
             <div className="w-24 h-24 bg-white/5 rounded-[32px] flex items-center justify-center mb-6 border border-white/5 shadow-xl">
                <Settings size={48} className="text-[#26b1c7]" />
             </div>
             <h2 className="text-2xl font-bold text-white uppercase tracking-tighter mb-2">Configurações Base</h2>
             <p className="text-zinc-500 font-medium tracking-[0.3em] text-[10px] uppercase">Módulo de permissões e chaves de API em desenvolvimento.</p>
          </div>
        );
      default:
        return <ContasReceberView />;
    }
  };

  return (
    <div className={cn(
      "workspace-theme flex h-screen w-full overflow-hidden transition-colors duration-500",
      isDarkMode ? "dark bg-[#0a0a0a] text-white" : "bg-[#f8fafc] text-slate-900"
    )} style={{ fontFamily: 'var(--font-main)' }}>
      
      {/* Sidebar REPRODUCED (Design Prafrota com Paleta Workspace) */}
      <WorkspaceSidebar 
        activeScreen={activeScreen} 
        onScreenChange={setActiveScreen} 
        isCollapsed={isSidebarCollapsed}
        onToggle={() => setIsSidebarCollapsed(!isSidebarCollapsed)}
      />

      {/* Main Content Area */}
      {/* Main Content Area */}
      <main className={cn(
        "flex-1 flex flex-col relative overflow-hidden overflow-x-hidden transition-all duration-300",
        isSidebarCollapsed ? "ml-[100px]" : "ml-[280px]"
      )}>
        
        {/* Header Simplificado */}
        <header className={cn(
          "h-16 px-10 sticky top-0 z-40 backdrop-blur-xl border-b flex items-center justify-between transition-all",
          isDarkMode ? "bg-[#0a0a0a]/80 border-white/5 shadow-2xl shadow-black/20" : "bg-white/80 border-slate-200"
        )}>
          <div className="flex items-center gap-4">
             {/* <div className="w-9 h-9 flex items-center justify-center">
                <img src={logo} alt="iTGUYS" className="h-6 w-auto" />
             </div> */}
             <h2 className={cn(
               "text-sm font-bold uppercase tracking-[0.2em]",
               isDarkMode ? "text-white" : "text-slate-800"
             )}>
               Financeiro / <span className="text-[#26b1c7]">{screenNames[activeScreen] || activeScreen}</span>
             </h2>
          </div>

          <div className="flex items-center gap-4">
              {/* Theme Toggle */}
              <button 
                onClick={() => setIsDarkMode(!isDarkMode)}
                className={cn(
                  "p-2.5 rounded-full transition-all shadow-sm border",
                  isDarkMode 
                    ? "bg-white/5 border-white/10 text-slate-400 hover:text-yellow-400 hover:bg-white/10" 
                    : "bg-white border-slate-200 text-slate-500 hover:text-orange-500 shadow-slate-200/50"
                )}
              >
                {isDarkMode ? <Sun size={20} /> : <Moon size={20} />}
              </button>

              {/* Logout explícito do Workspace */}
              <button
                onClick={handleLogout}
                className={cn(
                  "flex items-center gap-2 px-3 py-2 rounded-full text-xs font-bold uppercase tracking-[0.18em] transition-all",
                  "border border-red-500/40 text-red-400 hover:bg-red-500/10 hover:border-red-500/80"
                )}
              >
                <LogOut size={16} />
                Sair
              </button>
          </div>
        </header>

        {/* View Content Area - Clean & Direct */}
        <div className="flex-1 p-0 relative z-10 min-w-0 overflow-y-auto overflow-x-hidden custom-scrollbar flex flex-col">
           <div className="flex-1 w-full p-6 pb-20">
                {renderScreen()}
           </div>
        </div>

        {/* Footer Minimalista (Prafrota Style) */}
      </main>
      
      {/* Toast Notifications */}
      <Toaster 
        position="top-right"
        richColors
        closeButton
        duration={4000}
      />
    </div>
  );
};
