import React, { useState, useEffect, useCallback } from 'react';
import { FileSignature, Plus, Calendar, Clock, Briefcase, FileText, Trash2, X, Search, Eye } from 'lucide-react';
import { PageHeader } from '@/components/common/PageHeader';
import { Button } from '@/components/ui/button';
import { rhService } from '../../../services/rhService';
import { orgService } from '../../../services/orgService';
import { salaryService } from '../../../services/salaryService';
import { AgentDetailsModal } from '../components/AgentDetailsModal';
import { toast } from 'sonner';
import { format } from 'date-fns';
import { debounce } from 'lodash';

export const ContractsPage: React.FC = () => {
    const [contracts, setContracts] = useState<any[]>([]);
    const [agents, setAgents] = useState<any[]>([]);
    const [orgUnits, setOrgUnits] = useState<any[]>([]);
    const [positions, setPositions] = useState<any[]>([]);
    const [categories, setCategories] = useState<any[]>([]);
    const [grades, setGrades] = useState<any[]>([]);
    const [steps, setSteps] = useState<any[]>([]);

    const [selectedCategory, setSelectedCategory] = useState("");
    const [selectedGrade, setSelectedGrade] = useState("");

    const [loading, setLoading] = useState(true);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isDetailsOpen, setIsDetailsOpen] = useState(false);
    const [selectedAgent, setSelectedAgent] = useState<any>(null);
    const [editingContract, setEditingContract] = useState<any>(null);
    const [agentSearch, setAgentSearch] = useState("");
    const [searchingAgents, setSearchingAgents] = useState(false);
    const [showAgentSuggestions, setShowAgentSuggestions] = useState(false);
    const [selectedAgentForContract, setSelectedAgentForContract] = useState<any>(null);

    useEffect(() => {
        loadContracts();
        loadAgents();
        loadCareerBaseData();
    }, []);

    const loadContracts = async () => {
        try {
            setLoading(true);
            const data = await rhService.getContracts();
            setContracts(data);
        } catch (error) {
            toast.error('Erro ao carregar contratos');
        } finally {
            setLoading(false);
        }
    };

    const loadAgents = async (query: string = "") => {
        try {
            setSearchingAgents(true);
            const response = await rhService.getAgents({ page: 0, size: 20, query });
            setAgents(response.content);
        } catch (error) {
            console.error('Erro ao carregar agentes', error);
        } finally {
            setSearchingAgents(false);
        }
    };

    const debouncedSearch = useCallback(
        debounce((query: string) => loadAgents(query), 500),
        []
    );

    const handleAgentSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const val = e.target.value;
        setAgentSearch(val);
        debouncedSearch(val);
    };

    const handleOpenDetails = (contract: any) => {
        // Find agent from local list or fetch if needed
        const agent = agents.find(a => a.id === contract.agentId);
        if (agent) {
            setSelectedAgent(agent);
            setIsDetailsOpen(true);
        } else {
            // Se o agente n┬úo estiver na lista atual de agentes (devido a busca), buscar por ID
            rhService.getAgentById(contract.agentId).then(data => {
                setSelectedAgent(data);
                setIsDetailsOpen(true);
            });
        }
    };

    const handleEdit = async (contract: any) => {
        setEditingContract(contract);
        // Pre-carregar agentes se o agente do contrato n┬úo estiver na lista
        const agent = agents.find(a => a.id === contract.agentId);
        if (!agent) {
            const resp = await rhService.getAgentById(contract.agentId);
            setAgents([resp]);
        }

        // Carregar dados dependentes
        if (contract.orgUnit) {
            const data = await orgService.getPositions({ orgUnitId: contract.orgUnit });
            setPositions(Array.isArray(data) ? data : []);
        }

        if (contract.salaryCategory) {
            const data = await salaryService.getGradesByCategory(contract.salaryCategory);
            setGrades(data);
            setSelectedCategory(contract.salaryCategory);
        }

        if (contract.salaryGrade) {
            const data = await salaryService.getStepsByGrade(contract.salaryGrade);
            setSteps(data);
            setSelectedGrade(contract.salaryGrade);
        }

        if (agent) {
            setSelectedAgentForContract(agent);
        } else {
            const resp = await rhService.getAgentById(contract.agentId);
            setSelectedAgentForContract(resp);
        }

        setIsModalOpen(true);
    };

    const loadCareerBaseData = async () => {
        try {
            const [orgs, cats] = await Promise.all([
                orgService.getOrgUnits({ size: 100 }),
                salaryService.getAllCategories()
            ]);
            setOrgUnits(orgs.content);
            setCategories(cats);
        } catch (error) {
            console.error('Erro ao carregar dados base de carreira', error);
        }
    };

    const handleOrgChange = async (orgId: string) => {
        if (!orgId) {
            setPositions([]);
            return;
        }
        try {
            const data = await orgService.getPositions({ orgUnitId: orgId });
            setPositions(Array.isArray(data) ? data : []);
        } catch (error) {
            console.error('Erro ao carregar cargos', error);
        }
    };

    const handleCategoryChange = async (catId: string) => {
        setSelectedCategory(catId);
        setSelectedGrade("");
        setSteps([]);
        if (!catId) {
            setGrades([]);
            return;
        }
        try {
            const data = await salaryService.getGradesByCategory(catId);
            setGrades(data);
        } catch (error) {
            console.error('Erro ao carregar graus', error);
        }
    };

    const handleGradeChange = async (gradeId: string) => {
        setSelectedGrade(gradeId);
        if (!gradeId) {
            setSteps([]);
            return;
        }
        try {
            const data = await salaryService.getStepsByGrade(gradeId);
            setSteps(data);
        } catch (error) {
            console.error('Erro ao carregar escalões', error);
        }
    };

    const handleDelete = async (id: string) => {
        if (!confirm('Eliminar este contrato?')) return;
        try {
            await rhService.deleteContract(id);
            toast.success('Contrato eliminado');
            loadContracts();
        } catch (error) {
            toast.error('Erro ao eliminar');
        }
    };

    const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        const formData = new FormData(e.currentTarget);
        const data = {
            agent: { id: formData.get('agentId') },
            contractType: formData.get('contractType'),
            startDate: formData.get('startDate'),
            endDate: formData.get('endDate') || null,
            weeklyHours: parseInt(formData.get('weeklyHours') as string),
            orgUnit: formData.get('orgUnit'),
            position: formData.get('position'),
            salaryCategory: formData.get('salaryCategory'),
            salaryGrade: formData.get('salaryGrade'),
            salaryStep: formData.get('salaryStep'),
            legalActReference: formData.get('legalActReference'),
            isActive: true
        };

        try {
            if (editingContract) {
                await rhService.updateContract(editingContract.id, data);
                toast.success('Contrato atualizado com sucesso');
            } else {
                await rhService.saveContract(data);
                toast.success('Contrato registado e Agente activado');
            }
            setIsModalOpen(false);
            setEditingContract(null);
            setSelectedAgentForContract(null);
            setAgentSearch("");
            loadContracts();
        } catch (error) {
            toast.error(editingContract ? 'Erro ao atualizar contrato' : 'Erro ao registar contrato');
        }
    };

    const getTypeColor = (type: string) => {
        if (type?.includes('DEFINITIVA')) return 'bg-green-100 text-green-700';
        if (type?.includes('PROVISORIA')) return 'bg-yellow-100 text-yellow-700';
        return 'bg-blue-100 text-blue-700';
    };

    return (
        <div className="p-6 space-y-6">
            <PageHeader
                title="Contratos e Vínculos"
                description="Gestão de atos administrativos de admissão e contratos a termo"
                actions={
                    <Button onClick={() => setIsModalOpen(true)} className="flex items-center gap-2 text-white">
                        <Plus className="w-4 h-4" /> Novo Contrato
                    </Button>
                }
            />

            <div className="grid grid-cols-1 gap-4">
                {loading ? (
                    <div className="p-8 text-center bg-white rounded-lg border">Carregando...</div>
                ) : contracts.length === 0 ? (
                    <div className="p-12 text-center bg-white rounded-lg border flex flex-col items-center gap-3">
                        <Briefcase className="w-12 h-12 text-gray-200" />
                        <span className="text-gray-500">Nenhum vínculo contratual registado</span>
                    </div>
                ) : (
                    contracts.map((contract) => {
                        const agent = agents.find(a => a.id === contract.agentId);
                        return (
                            <div key={contract.id} className="bg-white p-6 rounded-lg shadow-sm border hover:shadow-md transition-shadow">
                                <div className="flex justify-between items-start">
                                    <div className="flex gap-4 items-center">
                                        <div className="p-3 bg-primary/5 rounded-full border border-primary/10">
                                            <FileText className="w-6 h-6 text-primary" />
                                        </div>
                                        <div>
                                            <div className="flex items-center gap-2">
                                                <span className="font-bold text-gray-900 text-lg">{agent?.fullName || `Agente: ${contract.agentId?.substring(0, 8)}`}</span>
                                                <span className={`px-2 py-0.5 rounded text-[10px] font-bold uppercase ${getTypeColor(contract.contractType)}`}>
                                                    {contract.contractType || 'VÍNCULO'}
                                                </span>
                                            </div>
                                            <p className="text-sm text-gray-500 font-mono">{agent?.matricula || 'Matrícula não carregada'}</p>
                                        </div>
                                    </div>
                                    <div className="flex gap-2">
                                        <Button variant="ghost" size="sm" onClick={() => handleEdit(contract)} className="flex items-center gap-1.5 hover:bg-primary/5 text-primary">
                                            <FileSignature className="w-4 h-4" /> Editar
                                        </Button>
                                        <Button variant="ghost" size="sm" onClick={() => handleOpenDetails(contract)} className="flex items-center gap-1.5 hover:bg-primary/5 text-primary">
                                            <Eye className="w-4 h-4" /> Detalhes
                                        </Button>
                                        <Button variant="ghost" size="sm" onClick={() => handleDelete(contract.id)} className="text-red-600 hover:bg-red-50">
                                            <Trash2 className="w-4 h-4" />
                                        </Button>
                                    </div>
                                </div>
                                <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm mt-6 pt-4 border-t border-gray-50">
                                    <div className="flex flex-col">
                                        <span className="text-[10px] uppercase font-bold text-gray-400 mb-1 flex items-center gap-1"><Clock className="w-3 h-3" /> Início</span>
                                        <span className="font-medium">{contract.startDate ? format(new Date(contract.startDate), 'dd/MM/yyyy') : '-'}</span>
                                    </div>
                                    <div className="flex flex-col">
                                        <span className="text-[10px] uppercase font-bold text-gray-400 mb-1 flex items-center gap-1"><Calendar className="w-3 h-3" /> Fim / Expiração</span>
                                        <span className="font-medium text-gray-600">{contract.endDate ? format(new Date(contract.endDate), 'dd/MM/yyyy') : 'Indeterminado'}</span>
                                    </div>
                                    <div className="flex flex-col">
                                        <span className="text-[10px] uppercase font-bold text-gray-400 mb-1 flex items-center gap-1"><Briefcase className="w-3 h-3" /> Carga Horária</span>
                                        <span className="font-medium text-primary bg-primary/5 px-2 py-0.5 rounded w-fit">{contract.weeklyHours}h/Semana</span>
                                    </div>
                                    <div className="flex flex-col">
                                        <span className="text-[10px] uppercase font-bold text-gray-400 mb-1 flex items-center gap-1"><FileSignature className="w-3 h-3" /> Ref. Legal (Ato)</span>
                                        <span className="font-medium text-gray-900 truncate" title={contract.legalActReference}>{contract.legalActReference || 'N/A'}</span>
                                    </div>
                                </div>
                            </div>
                        );
                    })
                )}
            </div>

            {isModalOpen && (
                <div
                    className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4"
                    onClick={() => setShowAgentSuggestions(false)}
                >
                    <div className="bg-white rounded-xl shadow-2xl max-w-3xl w-full overflow-hidden" onClick={(e) => e.stopPropagation()}>
                        <div className="px-6 py-4 border-b flex justify-between items-center bg-gray-50">
                            <h3 className="text-lg font-bold text-gray-900">{editingContract ? 'Editar Contrato / Vínculo' : 'Novo Contrato / Vínculo'}</h3>
                            <button onClick={() => { setIsModalOpen(false); setEditingContract(null); }} className="text-gray-400 hover:text-gray-600">
                                <X className="w-5 h-5" />
                            </button>
                        </div>
                        <form onSubmit={handleSubmit} className="p-6 space-y-4 max-h-[80vh] overflow-y-auto">
                            <div className="space-y-1 relative">
                                <label className="text-xs font-bold text-gray-500 uppercase">Seleccione o Agente (Nome ou Matrícula)</label>
                                <div className="relative">
                                    <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                                    <input
                                        type="text"
                                        placeholder={selectedAgentForContract ? `${selectedAgentForContract.fullName} (${selectedAgentForContract.matricula})` : "Digite para buscar agente..."}
                                        value={agentSearch}
                                        onChange={(e) => {
                                            setAgentSearch(e.target.value);
                                            debouncedSearch(e.target.value);
                                            setShowAgentSuggestions(true);
                                        }}
                                        onFocus={() => setShowAgentSuggestions(true)}
                                        className="w-full border rounded-lg pl-9 pr-3 py-2 text-sm focus:ring-2 focus:ring-primary focus:outline-none"
                                        required={!selectedAgentForContract}
                                    />
                                    {selectedAgentForContract && (
                                        <button
                                            type="button"
                                            onClick={() => {
                                                setSelectedAgentForContract(null);
                                                setAgentSearch("");
                                            }}
                                            className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-red-500"
                                        >
                                            <X className="w-4 h-4" />
                                        </button>
                                    )}
                                </div>
                                <input type="hidden" name="agentId" value={selectedAgentForContract?.id || editingContract?.agentId || ""} required />

                                {showAgentSuggestions && agentSearch.length > 0 && (
                                    <div className="absolute z-[60] left-0 right-0 top-full mt-1 bg-white border rounded-lg shadow-xl max-h-48 overflow-y-auto">
                                        {searchingAgents ? (
                                            <div className="p-3 text-xs text-center text-gray-500 animate-pulse">Buscando agentes...</div>
                                        ) : agents.length === 0 ? (
                                            <div className="p-3 text-xs text-center text-gray-500">Nenhum agente encontrado</div>
                                        ) : (
                                            agents.map(agent => (
                                                <div
                                                    key={agent.id}
                                                    onClick={() => {
                                                        setSelectedAgentForContract(agent);
                                                        setAgentSearch(""); // Limpa o texto da busca para mostrar o placeholder
                                                        setShowAgentSuggestions(false);
                                                    }}
                                                    className="p-3 border-b last:border-0 hover:bg-primary/5 cursor-pointer flex flex-col"
                                                >
                                                    <span className="text-sm font-bold text-gray-900">{agent.fullName}</span>
                                                    <span className="text-[10px] text-gray-500">Matrícula: {agent.matricula}</span>
                                                </div>
                                            ))
                                        )}
                                    </div>
                                )}
                            </div>

                            <div className="space-y-1">
                                <label className="text-xs font-bold text-gray-500 uppercase">Documentação Legal (Ato Administrativo)</label>
                                <div className="relative">
                                    <FileText className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                                    <input
                                        type="text"
                                        name="legalActReference"
                                        defaultValue={editingContract?.legalActReference}
                                        placeholder="Ex: Decreto nº 12/2023, Despacho nº 45..."
                                        required
                                        className="w-full border rounded-lg pl-9 pr-3 py-2 text-sm focus:ring-2 focus:ring-primary focus:outline-none"
                                    />
                                </div>
                            </div>

                            <div className="grid grid-cols-2 gap-4">
                                <div className="space-y-1">
                                    <label className="text-xs font-bold text-gray-500 uppercase">Tipo de Contrato</label>
                                    <select name="contractType" defaultValue={editingContract?.contractType} required className="w-full border rounded-lg p-2 text-sm focus:ring-2 focus:ring-primary focus:outline-none">
                                        <option value="NOMEAÇÃO_DEFINITIVA">Nomeação Definitiva</option>
                                        <option value="NOMEAÇÃO_PROVISORIA">Nomeação Provisória</option>
                                        <option value="CONTRATO_TERMO">Contrato a Termo</option>
                                        <option value="CONTRATO_PRESTAÇÃO_SERVIÇOS">Prestação de Serviços</option>
                                    </select>
                                </div>
                                <div className="space-y-1">
                                    <label className="text-xs font-bold text-gray-500 uppercase">Horas Semanais</label>
                                    <input type="number" name="weeklyHours" defaultValue={editingContract?.weeklyHours || "40"} required className="w-full border rounded-lg p-2 text-sm focus:ring-2 focus:ring-primary focus:outline-none" />
                                </div>
                            </div>

                            <div className="border-t pt-4 space-y-3">
                                <h4 className="text-xs font-black text-primary uppercase">Extensão de Carreira (Vínculo)</h4>

                                <div className="space-y-1">
                                    <label className="text-xs font-bold text-gray-500 uppercase">Unidade Organizacional</label>
                                    <select name="orgUnit" defaultValue={editingContract?.orgUnit} onChange={(e) => handleOrgChange(e.target.value)} required className="w-full border rounded-lg p-2 text-sm">
                                        <option value="">Selecione a unidade...</option>
                                        {orgUnits.map(unit => (
                                            <option key={unit.id} value={unit.id}>{unit.name}</option>
                                        ))}
                                    </select>
                                </div>

                                <div className="space-y-1">
                                    <label className="text-xs font-bold text-gray-500 uppercase">Cargo / Função</label>
                                    <select name="position" defaultValue={editingContract?.position} required className="w-full border rounded-lg p-2 text-sm">
                                        <option value="">Selecione o cargo...</option>
                                        {positions.map(pos => (
                                            <option key={pos.id} value={pos.id}>{pos.title}</option>
                                        ))}
                                    </select>
                                </div>

                                <div className="grid grid-cols-1 gap-3 border-l-2 border-primary/20 pl-3">
                                    <div className="space-y-1">
                                        <label className="text-xs font-bold text-gray-500 uppercase">Categoria Salarial</label>
                                        <select name="salaryCategory" value={selectedCategory} onChange={(e) => handleCategoryChange(e.target.value)} required className="w-full border rounded-lg p-2 text-sm">
                                            <option value="">Selecione a categoria...</option>
                                            {categories.map(cat => (
                                                <option key={cat.id} value={cat.id}>{cat.name}</option>
                                            ))}
                                        </select>
                                    </div>

                                    <div className="grid grid-cols-2 gap-3">
                                        <div className="space-y-1">
                                            <label className="text-xs font-bold text-gray-500 uppercase">Grau</label>
                                            <select name="salaryGrade" value={selectedGrade} onChange={(e) => handleGradeChange(e.target.value)} required className="w-full border rounded-lg p-2 text-sm">
                                                <option value="">Selecione...</option>
                                                {grades.map(grade => (
                                                    <option key={grade.id} value={grade.id}>{grade.name}</option>
                                                ))}
                                            </select>
                                        </div>

                                        <div className="space-y-1">
                                            <label className="text-xs font-bold text-gray-500 uppercase">Escalão</label>
                                            <select name="salaryStep" defaultValue={editingContract?.salaryStep} required className="w-full border rounded-lg p-2 text-sm">
                                                <option value="">Selecione...</option>
                                                {steps.map(step => (
                                                    <option key={step.id} value={step.id}>Escalão {step.stepNumber}</option>
                                                ))}
                                            </select>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div className="grid grid-cols-2 gap-4 border-t pt-4">
                                <div className="space-y-1">
                                    <label className="text-xs font-bold text-gray-500 uppercase">Data Início</label>
                                    <input type="date" name="startDate" defaultValue={editingContract?.startDate} required className="w-full border rounded-lg p-2 text-sm focus:ring-2 focus:ring-primary focus:outline-none" />
                                </div>
                                <div className="space-y-1">
                                    <label className="text-xs font-bold text-gray-500 uppercase">Data Fim (Opcional)</label>
                                    <input type="date" name="endDate" defaultValue={editingContract?.endDate} className="w-full border rounded-lg p-2 text-sm focus:ring-2 focus:ring-primary focus:outline-none" />
                                </div>
                            </div>

                            <div className="pt-4 flex gap-3">
                                <Button type="button" variant="outline" onClick={() => { setIsModalOpen(false); setEditingContract(null); }} className="flex-1">Cancelar</Button>
                                <Button type="submit" className="flex-1">{editingContract ? 'Atualizar' : 'Salvar e Activar'}</Button>
                            </div>
                        </form>
                    </div>
                </div>
            )}

            <AgentDetailsModal
                open={isDetailsOpen}
                onOpenChange={(open) => {
                    setIsDetailsOpen(open);
                    if (!open) setSelectedAgent(null);
                }}
                agent={selectedAgent}
            />
        </div>
    );
};
