import React, { useState, useMemo, useEffect } from 'react';
import ExcelTable from '../components/ExcelTable';
import { EmployeeDetailPanel } from '../components/EmployeeDetailPanel';
import { EmployeeEditModal } from '../components/EmployeeEditModal';
import { EmployeeCreateModal } from '../components/EmployeeCreateModal';
import { 
    Plus, 
    Bell, 
    RefreshCw, 
    MessageSquare, 
    X, 
    LayoutList, 
    CheckCircle2, 
    AlertCircle,
    BrainCircuit,
    User,
    ChevronRight,
    Search
} from 'lucide-react';
import { AnimatePresence, motion } from 'framer-motion';
import { useEmployees } from '../hooks/useEmployees';
import { RhFeedbackContainer, useRhFeedback } from '../components/RhFeedbackNotification';

export const EmployeesView = () => {
    const { 
        employees, 
        loading, 
        fetchEmployees, 
        searchInChat,
        setEmployees
    } = useEmployees();

    const { success, error, info, handleBackendError } = useRhFeedback();
    
    const [selectedEmployee, setSelectedEmployee] = useState(null);
    const [searchQuery, setSearchQuery] = useState('');
    const [chatResult, setChatResult] = useState(null);
    const [isChatModalOpen, setIsChatModalOpen] = useState(false);
    const [isEditModalOpen, setIsEditModalOpen] = useState(false);
    const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);

    useEffect(() => {
        fetchEmployees();
    }, [fetchEmployees]);

    // Colunas enriquecidas com base no mapeamento do banco de dados
    const columns = useMemo(() => [
        { field: 'id', header: 'ID', width: 70, className: 'font-mono text-[clamp(1rem,1.1vw,1.0625rem)] text-slate-500' },
        { 
            field: 'name', 
            header: 'Nome', 
            width: 250, 
            render: (row) => (
                <div className="flex items-center gap-3 w-full max-w-[250px]">
                    <div className="w-8 h-8 rounded-full bg-emerald-500/10 flex-shrink-0 flex items-center justify-center text-emerald-600 font-semibold text-[clamp(1rem,1.1vw,1.0625rem)]">
                        {row.name?.substring(0, 2).toUpperCase()}
                    </div>
                    <div className="flex flex-col min-w-0 flex-1">
                        <span className="font-semibold text-slate-800 dark:text-slate-200 leading-tight truncate block text-[clamp(1rem,1.2vw,1.125rem)]" title={row.name}>{row.name}</span>
                    </div>
                </div>
            ) 
        },
        { 
            field: 'email', 
            header: 'Email', 
            width: 200, 
            render: (row) => (
                <span className="text-[clamp(1rem,1.1vw,1.0625rem)] text-slate-600 dark:text-slate-300 font-normal truncate block" title={row.email}>
                    {row.email || 'Sem email corporativo'}
                </span>
            ) 
        },
        { field: 'role', header: 'Cargo', width: 180, className: 'text-[clamp(1rem,1.1vw,1.0625rem)] font-semibold text-slate-600 dark:text-slate-400' },
        { field: 'department', header: 'Empresa', width: 150, className: 'text-[clamp(1rem,1.1vw,1.0625rem)]' },
        { field: 'base', header: 'Base', width: 130, className: 'text-[clamp(1rem,1.1vw,1.0625rem)]' },
        { 
            field: 'status', 
            header: 'Status', 
            width: 130,
            render: (row) => {
                const statusRaw = row.status ? row.status.toUpperCase() : 'INATIVO';
                
                const statusStyles = {
                    'ATIVO': 'bg-emerald-100 text-emerald-700 border-emerald-200 dark:bg-emerald-500/10 dark:text-emerald-400 dark:border-emerald-500/20',
                    'FÉRIAS': 'bg-blue-100 text-blue-700 border-blue-200 dark:bg-blue-500/10 dark:text-blue-400 dark:border-blue-500/20',
                    'FERIAS': 'bg-blue-100 text-blue-700 border-blue-200 dark:bg-blue-500/10 dark:text-blue-400 dark:border-blue-500/20',
                    'DESLIGADO': 'bg-rose-100 text-rose-700 border-rose-200 dark:bg-rose-500/10 dark:text-rose-400 dark:border-rose-500/20',
                    'DEMITIDO': 'bg-rose-100 text-rose-700 border-rose-200 dark:bg-rose-500/10 dark:text-rose-400 dark:border-rose-500/20',
                    'INATIVO': 'bg-slate-100 text-slate-700 border-slate-200 dark:bg-slate-500/10 dark:text-slate-400 dark:border-slate-500/20',
                    'AFASTADO': 'bg-amber-100 text-amber-700 border-amber-200 dark:bg-amber-500/10 dark:text-amber-400 dark:border-amber-500/20',
                };

                const defaultStyle = 'bg-slate-100 text-slate-700 border-slate-200 dark:bg-slate-800 dark:text-slate-300 dark:border-slate-700';

                return (
                    <span className={`px-2.5 py-1 rounded-lg text-[clamp(1rem,1.1vw,1.0625rem)] font-medium uppercase border shadow-sm tracking-wide ${statusStyles[statusRaw] || defaultStyle}`}>
                        {row.status}
                    </span>
                );
            }
        },
        { 
            field: 'cnh_status', 
            header: 'CNH', 
            width: 120,
            render: (row) => {
                const config = {
                    'valida': { label: 'Válida', color: 'text-emerald-500', icon: CheckCircle2 },
                    'proxima_vencer': { label: 'Próxima', color: 'text-amber-500', icon: AlertCircle },
                    'vencida': { label: 'Vencida', color: 'text-rose-500', icon: AlertCircle }
                };
                const cfg = config[row.cnh_status] || { label: 'N/A', color: 'text-slate-400', icon: AlertCircle };
                const Icon = cfg.icon;
                return (
                    <div className={`flex items-center gap-1.5 text-[clamp(1rem,1.1vw,1.0625rem)] font-medium ${cfg.color}`}>
                        <Icon size={12} />
                        {cfg.label}
                    </div>
                );
            }
        },
        { field: 'phone', header: 'Telefone', width: 140, className: 'text-[clamp(1rem,1.1vw,1.0625rem)] font-mono' },
        { field: 'admissionDate', header: 'Adm.', width: 100, className: 'text-[clamp(1rem,1.1vw,1.0625rem)]' },
    ], []);

    const filterDefs = [
        { field: 'busca', label: 'Nome', type: 'text', placeholder: 'Buscar colaborador...' },
        { field: 'cargo', label: 'Cargo', type: 'text' },
        { field: 'base', label: 'Base', type: 'text' },
        { field: 'idcolaborador', label: 'ID', type: 'text' },
        { 
            field: 'cnh_status', 
            label: 'Status CNH', 
            type: 'select', 
            options: [
                { label: 'Válida', value: 'valida' },
                { label: 'Próxima a vencer', value: 'proxima_vencer' },
                { label: 'Vencida', value: 'vencida' }
            ] 
        }
    ];

    const handleEdit = (employee) => {
        setSelectedEmployee(employee);
    };

    const handleOpenEdit = (fullEmployee = null) => {
        if (fullEmployee && typeof fullEmployee === 'object') {
            console.log('📝 Atualizando dados para edição:', fullEmployee);
            setSelectedEmployee(fullEmployee);
        }
        setIsEditModalOpen(true);
    };

    const handleClosePanel = () => {
        setSelectedEmployee(null);
    };

    const handleChatSearch = async () => {
        if (!searchQuery) return;
        
        info('Iniciando Consulta', 'A IA está analisando a base de dados...');
        try {
            const result = await searchInChat(searchQuery);
            
            if (result && result.success) {
                setChatResult(result);
                setIsChatModalOpen(true);
                success('Consulta Concluída', 'Dados extraídos com sucesso.');
                
                // Verifica se temos dados para exibir na tabela
                if (result.dados && Array.isArray(result.dados) && result.dados.length > 0) {
                    const firstItem = result.dados[0];
                    // Identifica se é uma lista de colaboradores ou dados agregados/estatísticos
                    const isEmployeeList = 'colaboradores' in firstItem || 'nome' in firstItem;

                    if (isEmployeeList) {
                        const mappedResults = result.dados.map(emp => {
                            // Lógica de cálculo de Status CNH igual ao hook useEmployees
                            let cnhStatus = 'valida';
                            if (emp.validade_cnh) {
                                const expiry = new Date(emp.validade_cnh);
                                const now = new Date();
                                const diffDays = Math.ceil((expiry - now) / (1000 * 60 * 60 * 24));
                                
                                if (diffDays < 0) cnhStatus = 'vencida';
                                else if (diffDays <= 30) cnhStatus = 'proxima_vencer';
                            } else if (searchQuery.toLowerCase().includes('vencid')) {
                                // Fallback para inferir status baseada na pergunta se a data não vier
                                cnhStatus = 'vencida';
                            }

                            return {
                                id: emp.idcolaborador || Math.random(),
                                name: emp.colaboradores || emp.nome,
                                email: emp.email_corporativo || 'Não informado',
                                phone: emp.telefone || '-',
                                role: emp.cargo || '-',
                                department: emp.empresa || emp.cliente || '-',
                                base: emp.base || '-',
                                status: emp.status_contrato || 'Ativo',
                                cnh_status: cnhStatus,
                                admissionDate: emp.data_admissao ? new Date(emp.data_admissao).toLocaleDateString() : '-',
                                manager: emp.responsavel_direto || emp.responsavel_direto_validado || '-'
                            };
                        });
                        setEmployees(mappedResults);
                    }
                }
            } else {
                error('Aviso', 'Não foi possível processar a consulta inteligente.');
            }
        } catch (err) {
            handleBackendError(err);
        }
    };

    return (
        <div className="theme-rh flex-1 flex flex-col h-full w-full overflow-hidden bg-slate-50/50 dark:bg-[#0a0a0a]">
            {/* Header Premium */}
            <div className="flex-shrink-0 border-b border-slate-200 dark:border-white/5 px-8 py-4 bg-white dark:bg-[#1b1b1b] shadow-sm rounded-t-2xl">
                <div className="flex items-center gap-4 mb-4">
                    <div className="p-2.5 bg-emerald-500/10 rounded-3xl">
                        <LayoutList className="text-emerald-500" size={24} />
                    </div>
                    <div className="flex-1">
                        <div className="flex items-center gap-2">
                            <h1 className="text-[clamp(1rem,1.8vw,1.5rem)] font-semibold text-slate-800 dark:text-white tracking-tight leading-tight break-words">
                                Gestão de Colaboradores
                            </h1>
                            {loading && <RefreshCw size={14} className="animate-spin text-emerald-500" />}
                        </div>
                        <p className="text-[clamp(1rem,1.1vw,1.0625rem)] text-slate-400 font-medium uppercase tracking-widest">
                            Base de Talentos & Operação
                        </p>
                    </div>
                </div>

                <div className="flex items-center gap-4 flex-wrap">
                    <div className="relative group flex-1 min-w-[280px]">
                        <div className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400">
                            <BrainCircuit size={18} />
                        </div>
                        <input 
                            type="text" 
                            placeholder="IA Chat: 'Quem é motorista?'"
                            value={searchQuery}
                            onChange={(e) => setSearchQuery(e.target.value)}
                            onKeyDown={(e) => e.key === 'Enter' && handleChatSearch()}
                            className="w-full pl-12 pr-4 py-3 bg-slate-100 dark:bg-white/5 border-none rounded-xl text-[clamp(1rem,1.1vw,1.0625rem)] font-semibold focus:ring-2 focus:ring-emerald-500/50 transition-all placeholder:text-slate-400"
                        />
                        {searchQuery && (
                            <button 
                                onClick={() => { setSearchQuery(''); fetchEmployees(); }}
                                className="absolute right-3 top-1/2 -translate-y-1/2 p-1 hover:bg-slate-200 dark:hover:bg-white/10 rounded-lg transition-colors"
                            >
                                <X size={14} />
                            </button>
                        )}
                    </div>
                    
                    <button 
                        onClick={() => setIsCreateModalOpen(true)}
                        className="flex items-center gap-2 px-4 sm:px-6 py-3 bg-emerald-600 text-white rounded-lg text-[clamp(0.875rem,1.2vw,1rem)] font-semibold uppercase tracking-wider hover:bg-emerald-700 transition-all shadow-lg shadow-emerald-600/20 active:scale-95 whitespace-nowrap"
                    >
                        <Plus size={16} /> Novo Colaborador
                    </button>
                </div>
            </div>

            {/* Content Area with Table */}
            <div className="flex-1 flex flex-col min-h-0">
                <div className="flex-1 p-6 overflow-hidden">
                    <div className="h-full bg-white dark:bg-[#1b1b1b] rounded-2xl border border-slate-200 dark:border-white/5 overflow-hidden flex flex-col shadow-xl shadow-slate-200/50 dark:shadow-none">
                       <ExcelTable 
                            data={employees}
                            columns={columns}
                            filterDefs={filterDefs}
                            onRowClick={handleEdit}
                            pageSize={10}
                            loading={loading}
                       />
                    </div>
                </div>
            </div>

            {/* Modal de Resultado da IA */}
            <AnimatePresence>
                {isChatModalOpen && chatResult && (
                    <div className="fixed inset-0 z-[200] flex items-center justify-center p-4 bg-slate-900/40 backdrop-blur-md">
                        <motion.div
                            initial={{ opacity: 0, scale: 0.9, y: 20 }}
                            animate={{ opacity: 1, scale: 1, y: 0 }}
                            exit={{ opacity: 0, scale: 0.9, y: 20 }}
                            className="w-full max-w-2xl bg-white dark:bg-[#1b1b1b] rounded-xl shadow-2xl border border-slate-200 dark:border-white/10 overflow-hidden"
                        >
                            <div className="p-8 border-b border-slate-100 dark:border-white/5 flex items-center justify-between bg-emerald-500/5">
                                <div className="flex items-center gap-4">
                                    <div className="p-3 bg-emerald-500 rounded-2xl shadow-lg shadow-emerald-500/30">
                                        <BrainCircuit size={24} className="text-white" />
                                    </div>
                                    <div>
                                        <h2 className="text-[clamp(1.25rem,2.4vw,1.875rem)] font-semibold text-slate-800 dark:text-white leading-tight">Insight da IA</h2>
                                        <p className="text-[clamp(1rem,1.1vw,1.0625rem)] text-emerald-600 dark:text-emerald-400 font-medium uppercase tracking-wider">Análise Concluída</p>
                                    </div>
                                </div>
                                <button 
                                    onClick={() => setIsChatModalOpen(false)}
                                    className="p-2 hover:bg-slate-200 dark:hover:bg-white/10 rounded-2xl transition-colors"
                                >
                                    <X size={20} />
                                </button>
                            </div>
                            
                            <div className="p-8 max-h-[60vh] overflow-y-auto custom-scrollbar">
                                <div className="bg-slate-50 dark:bg-white/5 p-6 rounded-lg mb-6">
                                    <p className="text-slate-700 dark:text-slate-300 text-[clamp(1rem,1.2vw,1.125rem)] font-normal leading-relaxed">
                                        {chatResult.resposta}
                                    </p>
                                </div>
                                
                                {chatResult.dados && chatResult.dados.length > 0 && (
                                    <div className="space-y-3">
                                        <h3 className="text-[clamp(1rem,1.1vw,1.0625rem)] font-semibold uppercase text-slate-400 tracking-widest pl-2">Resultados Estruturados</h3>
                                        
                                        {/* Verifica o tipo de dado para decidir como renderizar */}
                                        {('colaboradores' in chatResult.dados[0] || 'nome' in chatResult.dados[0]) ? (
                                            /* Renderização: Lista de Colaboradores */
                                            <div className="grid grid-cols-1 gap-2">
                                                {chatResult.dados.slice(0, 5).map((item, idx) => (
                                                    <div key={idx} className="flex items-center justify-between p-4 bg-white dark:bg-white/5 border border-slate-100 dark:border-white/5 rounded-xl hover:border-emerald-500/30 transition-all cursor-pointer group">
                                                        <div className="flex items-center gap-3">
                                                            <div className="w-10 h-10 rounded-xl bg-slate-100 dark:bg-white/5 flex items-center justify-center text-slate-500 group-hover:bg-emerald-500/10 group-hover:text-emerald-600 transition-colors">
                                                                <User size={20} />
                                                            </div>
                                                            <div>
                                                                <p className="text-[clamp(1rem,1.2vw,1.125rem)] font-semibold text-slate-800 dark:text-slate-200">{item.colaboradores || item.nome}</p>
                                                                <p className="text-[clamp(1rem,1.1vw,1.0625rem)] text-slate-400 font-medium uppercase">{item.cargo || 'Cargo não informado'}</p>
                                                            </div>
                                                        </div>
                                                        <ChevronRight size={16} className="text-slate-300 group-hover:text-emerald-500 transition-colors" />
                                                    </div>
                                                ))}
                                                {chatResult.dados.length > 5 && (
                                                    <p className="text-center text-[clamp(1rem,1.1vw,1.0625rem)] text-slate-400 font-medium uppercase mt-2">
                                                        + {chatResult.dados.length - 5} outros resultados aplicados na tabela atrás
                                                    </p>
                                                )}
                                            </div>
                                        ) : (
                                            /* Renderização: Dados Agregados/Estatísticos */
                                            <div className="space-y-2">
                                                {chatResult.dados.map((item, idx) => {
                                                    // Determina chave e valor dinamicamente
                                                    // Geralmente temos chaves como 'cargo', 'empresa' junto com 'quantidade' ou 'total'
                                                    const countKey = Object.keys(item).find(k => k === 'quantidade' || k === 'total') || 'valor';
                                                    const labelKey = Object.keys(item).find(k => k !== 'quantidade' && k !== 'total') || 'item';
                                                    
                                                    return (
                                                        <div key={idx} className="flex items-center justify-between p-3 bg-white dark:bg-white/5 rounded-lg border border-slate-100 dark:border-white/5">
                                                            <div className="flex flex-col">
                                                                <span className="text-[clamp(1rem,1.2vw,1.125rem)] font-semibold text-slate-700 dark:text-slate-300">
                                                                    {item[labelKey] || 'N/A'}
                                                                </span>
                                                                <span className="text-[clamp(1rem,1.1vw,1.0625rem)] text-slate-400 uppercase">
                                                                    {labelKey.replace('_', ' ')}
                                                                </span>
                                                            </div>
                                                            <div className="px-3 py-1 bg-emerald-500/10 text-emerald-600 rounded-xl font-semibold text-[clamp(1rem,1.2vw,1.125rem)]">
                                                                {item[countKey]}
                                                            </div>
                                                        </div>
                                                    );
                                                })}
                                            </div>
                                        )}
                                    </div>
                                )}
                            </div>
                            
                            <div className="p-8 bg-slate-50 dark:bg-white/2 border-t border-slate-100 dark:border-white/5 flex justify-end">
                                <button 
                                    onClick={() => setIsChatModalOpen(false)}
                                    className="px-8 py-3 bg-emerald-600 text-white rounded-xl text-[clamp(1rem,1.1vw,1.0625rem)] font-semibold uppercase tracking-widest shadow-lg shadow-emerald-500/20"
                                >
                                    Entendido
                                </button>
                            </div>
                        </motion.div>
                    </div>
                )}
            </AnimatePresence>

            {/* Side Panel - RESPONSIVO */}
            <AnimatePresence>
                {selectedEmployee && (
                    <>
                        <motion.div
                            initial={{ opacity: 0 }}
                            animate={{ opacity: 1 }}
                            exit={{ opacity: 0 }}
                            onClick={handleClosePanel}
                            className="fixed inset-0 bg-black/50 backdrop-blur-sm z-[100]"
                        />
                        <motion.div
                            initial={{ x: '100%' }}
                            animate={{ x: 0 }}
                            exit={{ x: '100%' }}
                            transition={{ type: 'spring', damping: 30, stiffness: 300 }}
                            className="fixed right-0 top-0 bottom-0 w-full md:w-[85%] lg:w-[85%] xl:w-[85%] z-[101]"
                        >
                            <div className="h-full w-full shadow-[-20px_0_50px_-10px_rgba(0,0,0,0.1)] overflow-hidden bg-white dark:bg-[#1b1b1b] border-l border-slate-200 dark:border-white/5">
                                <EmployeeDetailPanel 
                                    employee={selectedEmployee} 
                                    onClose={handleClosePanel} 
                                    onEdit={handleOpenEdit}
                                    onUpdate={() => fetchEmployees()}
                                />
                            </div>
                        </motion.div>
                    </>
                )}
            </AnimatePresence>

            {/* Modal de Edição */}
            <EmployeeEditModal 
                isOpen={isEditModalOpen}
                onClose={() => setIsEditModalOpen(false)}
                employee={selectedEmployee}
                onUpdate={() => {
                    // Após a edição, recarrega e fecha o painel detalhado conforme solicitado
                    fetchEmployees();
                    setSelectedEmployee(null);
                }}
            />

            {/* Modal de Criação */}
            <EmployeeCreateModal 
                isOpen={isCreateModalOpen}
                onClose={() => setIsCreateModalOpen(false)}
                onSuccess={() => {
                    fetchEmployees();
                }}
            />

            <RhFeedbackContainer />
        </div>
    );
};
