import React, { useState, useEffect } from 'react';
import { AppLayout } from '@/components/layout/AppLayout';
import { FinanceiroV2Sidebar } from './components/FinanceiroV2Sidebar';
import { DashboardView } from './views/DashboardView';
import { FluxoCaixaView } from './views/FluxoCaixaView';
import { ContasPagarView } from './views/ContasPagarView';
import { ContasReceberView } from './views/contas-receber/ContasReceberView';
import { ConciliacaoView } from './views/conciliacao-v2/ConciliacaoView';
import { RelatoriosView } from './views/RelatoriosView';

// External Module views
import { DashboardView as FleetDashboardView } from '../fleet-v2/views/DashboardView';
import { FleetManagementView } from '../fleet-v2/views/FleetManagementView';
import { FuelingView } from '../fleet-v2/views/FuelingView';
import { MaintenanceView } from '../fleet-v2/views/MaintenanceView';
import { HRDashboard } from '../rh/components/HRDashboard';
import logo from '@/assets/Img/Util/Pralog/pralog-preenchido-branco-logo-01-01.png';

import { useAuthContext } from '@/components/shared/AuthProvider';
import { useNavigate } from 'react-router-dom';
import { Clock, Construction, Building, Plus, CalendarCheck, Receipt } from 'lucide-react';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { BoletoCreationDialog } from './components/BoletoCreationDialog';
import { useBoletos } from './hooks/useBoletos';

/**
 * Placeholder for views not yet migrated or implemented with full parity.
 */
const PlaceholderView = ({ title }) => (
  <div className="flex flex-col items-center justify-center min-h-[60vh] text-center space-y-[clamp(1rem,2vw,1.5rem)] animate-in fade-in slide-in-from-bottom-10 duration-700">
    <div className="w-[clamp(5rem,8vw,6rem)] h-[clamp(5rem,8vw,6rem)] bg-emerald-500/10 rounded-3xl flex items-center justify-center border border-emerald-500/20 shadow-2xl shadow-emerald-900/10">
      <Construction className="w-[clamp(2.5rem,4vw,3rem)] h-[clamp(2.5rem,4vw,3rem)] text-emerald-500" />
    </div>
    <div>
      <h2 className="text-[clamp(1.5rem,3vw,2.25rem)] font-semibold text-slate-900 tracking-tight mb-[clamp(0.5rem,1vw,0.75rem)]">{title}</h2>
      <p className="text-[clamp(0.875rem,1.1vw,1rem)] text-slate-500 max-w-md mx-auto font-normal">
        Esta funcionalidade está sendo preparada para o novo ambiente premium. 
        Em breve você terá acesso a todos os recursos com visual 1:1.
      </p>
    </div>
    <div className="flex gap-[clamp(0.75rem,1vw,1rem)]">
       <div className="px-[clamp(0.75rem,1vw,1rem)] py-[clamp(0.5rem,0.8vh,0.75rem)] bg-slate-100 rounded-lg border border-slate-200 text-[clamp(0.625rem,0.8vw,0.75rem)] font-semibold text-slate-500 uppercase tracking-widest">
         Módulo: Em Desenvolvimento
       </div>
    </div>
  </div>
);

/**
 * HeaderExtras Component - Restores the Ticker and Real-time Clock
 */
const HeaderExtras = () => {
  const [time, setTime] = useState(new Date().toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' }));
  const { state, actions } = useBoletos();
  const [isCreationOpen, setIsCreationOpen] = useState(false);
  const [creationMode, setCreationMode] = useState('AVULSO');

  useEffect(() => {
    const timer = setInterval(() => {
      setTime(new Date().toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' }));
    }, 60000);
    return () => clearInterval(timer);
  }, []);

  const tickers = [
    { label: 'DÓLAR', value: 'R$ 5.37', trend: 'down', change: '0.4%' },
    { label: 'EURO', value: 'R$ 6.26', trend: 'up', change: '0.2%' },
    { label: 'SELIC', value: '0.055131%', trend: 'neutral', change: '-' },
    { label: 'IPCA', value: '0.33%', trend: 'neutral', change: '-' },
  ];

  const handleOpenCreation = (mode) => {
    setCreationMode(mode);
    setIsCreationOpen(true);
  };

  const handleCreate = async (formData, mode) => {
    let success = false;
    if (mode === 'AGENDAMENTO') {
      success = await actions.agendarBoletosGlobal(formData);
    } else {
      success = await actions.createBoleto(formData, mode);
    }
    if (success) setIsCreationOpen(false);
  };

  return (
    <div className="hidden lg:flex items-center gap-[clamp(1.5rem,2.5vw,2.5rem)]">
      {/* Quick Actions */}
      <div className="flex items-center gap-3 pr-4 border-r border-slate-800">
        <Button 
          size="sm" 
          variant="outline"
          className="bg-blue-500/10 border-blue-500/20 text-blue-400 hover:bg-blue-500/20 hover:text-blue-300 h-9 transition-all cursor-pointer"
          onClick={() => handleOpenCreation('MENSAL')}
        >
          <Receipt className="w-4 h-4 mr-2" />
          Nova Receita
        </Button>
        <Button 
          size="sm" 
          variant="outline"
          className="bg-amber-500/10 border-amber-500/20 text-amber-400 hover:bg-amber-500/20 hover:text-amber-300 h-9 transition-all cursor-pointer"
          onClick={() => handleOpenCreation('AGENDAMENTO')}
        >
          <CalendarCheck className="w-4 h-4 mr-2" />
          Agendar
        </Button>
      </div>

      <div className="flex items-center gap-[clamp(1rem,2vw,2rem)]">
        {tickers.map((ticker, index) => (
          <div key={index} className="flex flex-col items-start gap-[clamp(0.125rem,0.2vw,0.25rem)]">
             <span className="text-[clamp(0.5625rem,0.7vw,0.625rem)] font-semibold text-slate-500 uppercase tracking-widest">{ticker.label}</span>
             <div className="flex items-center gap-[clamp(0.25rem,0.4vw,0.375rem)]">
               <span className="text-[clamp(0.75rem,0.9vw,0.875rem)] font-semibold text-slate-900 dark:text-slate-200 tracking-tight whitespace-nowrap">{ticker.value}</span>
               {ticker.trend === 'up' && <div className="w-0 h-0 border-l-[3px] border-l-transparent border-r-[3px] border-r-transparent border-b-[5px] border-b-emerald-500" />}
               {ticker.trend === 'down' && <div className="w-0 h-0 border-l-[3px] border-l-transparent border-r-[3px] border-r-transparent border-t-[5px] border-t-rose-500" />}
               {ticker.change !== '-' && <span className={cn("text-[clamp(0.5625rem,0.7vw,0.625rem)] font-semibold", ticker.trend === 'up' ? "text-emerald-500" : "text-rose-500")}>{ticker.change}</span>}
             </div>
          </div>
        ))}
      </div>

      <div className="flex items-center gap-[clamp(0.75rem,1vw,1rem)] pl-[clamp(1rem,2vw,2rem)] border-l border-slate-200 dark:border-slate-800">
        <span className="font-mono text-[clamp(1rem,1.2vw,1.125rem)] font-semibold text-slate-900 dark:text-slate-200 tracking-wider tabular-nums">
          {time}
        </span>
        <div className="w-[clamp(2rem,3vw,2.5rem)] h-[clamp(2rem,3vw,2.5rem)] rounded-lg bg-slate-100 dark:bg-slate-800/50 flex items-center justify-center border border-slate-200 dark:border-slate-700/50">
           <span className="text-[clamp(0.625rem,0.8vw,0.75rem)] font-semibold text-emerald-600 dark:text-emerald-500">AD</span>
        </div>
      </div>

      <BoletoCreationDialog 
        open={isCreationOpen}
        onOpenChange={setIsCreationOpen}
        creationMode={creationMode}
        empresas={state.empresas}
        isCreating={state.isCreating}
        onCreateBoleto={handleCreate}
      />
    </div>
  );
};

const Logo = ({ size = 22, className }) => (
  <img 
    src={logo} 
    alt="Integra Finance" 
    className={cn("object-contain", className)}
    style={{ width: size, height: size }}
  />
);

/**
 * Main Controller for Financeiro V2 Environment.
 * Manages views and state within this domain.
 */
export const FinanceiroV2App = () => {
  const [currentView, setCurrentView] = React.useState('dashboard');
  const { logout, user } = useAuthContext();
  const navigate = useNavigate();

  const handleLogout = () => {
    logout('financeiro');
    navigate('/plataforma/auth/login-finance');
  };

  const getTitle = () => {
    switch (currentView) {
      case 'dashboard': return 'Dashboard';
      case 'fluxo': return 'Fluxo de Caixa';
      case 'pagar': return 'Contas a Pagar';
      case 'receber': return 'Contas a Receber';
      case 'conciliacao': return 'Conciliação Bancária';
      case 'relatorios': return 'Relatórios e BI';
      case 'ponto': return 'Bater Ponto';
      case 'gestao-rh': return 'Gestão de Equipe';
      case 'frota-overview': return 'Visão Geral da Frota';
      case 'frota-veiculos': return 'Gestão de Veículos';
      case 'frota-abastecimento': return 'Controle de Abastecimento';
      case 'frota-manutencao': return 'Controle de Manutenção';
      case 'frota-pneus': return 'Gestão de Pneus';
      case 'frota-multas': return 'Gestão de Multas';
      case 'admin-clientes': return 'Gestão de Clientes';
      default: return 'Financeiro V2';
    }
  };

  const getSubtitle = () => {
    switch (currentView) {
      case 'dashboard': return 'Visão Geral & Indicadores';
      case 'fluxo': return 'Visão Estratégica & Forecast';
      case 'pagar': return 'Gestão de Saídas e Fornecedores';
      case 'receber': return 'Gestão de Entradas e Cobranças';
      case 'conciliacao': return 'Gestão de Conciliação e Extratos';
      case 'relatorios': return 'Análise de Dados & BI';
      case 'ponto': return 'Registro de Jornada de Trabalho';
      case 'gestao-rh': return 'Administração de Colaboradores';
      case 'frota-overview': return 'Status e KPIs Operacionais';
      case 'frota-veiculos': return 'Inventário e Disponibilidade';
      case 'frota-abastecimento': return 'Custos e Consumo de Combustível';
      case 'frota-manutencao': return 'Preventivas e Corretivas';
      case 'frota-pneus': return 'Ciclo de Vida e Trocas';
      case 'frota-multas': return 'Infrações e Condutores';
      case 'admin-clientes': return 'Base de Dados de Clientes';
      default: return 'Sistema Integrado';
    }
  };

  const handleNavigate = (view) => {
    console.log('[FinanceiroV2App] handleNavigate chamado com:', view);
    try {
        setCurrentView(view);
    } catch (error) {
        console.error('[FinanceiroV2App] Erro ao setar view:', error);
    }
  };

  const renderView = () => {
    // Separar view principal de sub-view (ex: 'conciliacao/extrato')
    const parts = (currentView || '').split('/');
    const mainView = parts[0];
    const subView = parts[1];
    
    console.log(`[FinanceiroV2App] Renderizando: ${currentView}`);
    console.log(`[FinanceiroV2App] Main: ${mainView}, Sub: ${subView}`);

    switch (mainView) {
      // Financeiro
      case 'dashboard': return <DashboardView onNavigate={handleNavigate} />;
      case 'fluxo': return <FluxoCaixaView />;
      case 'pagar': return <ContasPagarView initialView={subView} />; // Preparando para futuro
      case 'receber': return <ContasReceberView initialView={subView} />;
      case 'conciliacao': return <ConciliacaoView initialView={subView} />;
      case 'relatorios': return <RelatoriosView />;
      
      // Recursos Humanos
      case 'ponto': return <PlaceholderView title="Bater Ponto" />;
      case 'gestao-rh': return <HRDashboard />;

      // Gestão de Frota
      case 'frota-overview': return <FleetDashboardView />;
      case 'frota-veiculos': return <FleetManagementView />;
      case 'frota-abastecimento': return <FuelingView />;
      case 'frota-manutencao': return <MaintenanceView />;
      case 'frota-pneus': return <PlaceholderView title="Gestão de Pneus" />;
      case 'frota-multas': return <PlaceholderView title="Gestão de Multas" />;

      // Administrativo
      case 'admin-clientes': return <PlaceholderView title="Gestão de Clientes" />;

      default: return <DashboardView />;
    }
  };

  if (!user) return null;

  return (
    <div className="theme-financeiro">
      <AppLayout 
        brandIcon={Logo}
        brandName="Integra"
        brandColorClass="bg-white shadow-xl border border-slate-100"
        title={getTitle()} 
        subtitle={getSubtitle()}
        onLogout={handleLogout}
        metadataType="finance"
        userName={user.name || 'Gestor Financeiro'}
        headerExtras={<HeaderExtras />}
        sidebar={<FinanceiroV2Sidebar currentView={currentView} onViewChange={setCurrentView} onLogout={handleLogout} />}
        headerClassName="bg-white dark:bg-[#0b1120] border-slate-200 dark:border-slate-900 h-24"
        sidebarClassName="bg-white dark:bg-[#0f172a] border-slate-100 dark:border-slate-900 shadow-xl"
      >
        <div className="min-h-[calc(100vh-160px)] font-inter text-slate-700 transition-colors duration-500 relative bg-slate-50 dark:bg-[#030712]">
           {/* Global Background Glow Financeiro */}
           <div className="absolute top-0 right-1/4 w-[800px] h-[800px] bg-emerald-500/[0.04] rounded-full blur-[140px] pointer-events-none" />
           
          <div className="animate-in fade-in zoom-in-95 duration-500 relative z-10 p-8">
            {renderView()}
          </div>
        </div>
      </AppLayout>
    </div>
  );
};

export default FinanceiroV2App;
