import { useState, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
} from '@/components/ui/form';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Checkbox } from '@/components/ui/checkbox';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { 
    User, 
    FileSignature, 
    CreditCard, 
    ChevronRight, 
    ChevronLeft,
    CheckCircle2,
    Circle
} from 'lucide-react';
import { rhService } from '@/services/rhService';
import { orgService } from '@/services/orgService';
import { salaryService } from '@/services/salaryService';
import { commonService } from '@/services/commonService';
import { toast } from 'sonner';
import { AgentDTO } from '@/types/rh';
import { BankDTO } from '@/types/common';

// Schema para dados do agente
const agentSchema = z.object({
    matricula: z.string().min(1, 'Matrícula é obrigatória'),
    nif: z.string().min(1, 'NIF é obrigatório'),
    biNumber: z.string().min(1, 'Número de BI é obrigatório'),
    fullName: z.string().min(1, 'Nome completo é obrigatório'),
    birthDate: z.string().min(1, 'Data de nascimento é obrigatória'),
    hireDate: z.string().min(1, 'Data de admissão é obrigatória'),
    posseDate: z.string().min(1, 'Data de posse é obrigatória'),
    status: z.string().default('REGISTERED'),
    literaryQualification: z.string().optional(),
    eligibleDependentsCount: z.string().default('0'),
    nationality: z.string().optional(),
    email: z.string().email('Email inválido').optional().or(z.literal('')),
    phone: z.string().optional(),
    address: z.string().optional(),
    orgUnit: z.string().optional(),
    position: z.string().optional(),
    salaryCategory: z.string().optional(),
    salaryGrade: z.string().optional(),
    salaryStep: z.string().optional(),
});

// Schema para contrato
const contractSchema = z.object({
    contractType: z.string().min(1, 'Tipo de contrato é obrigatório'),
    startDate: z.string().min(1, 'Data de início é obrigatória'),
    endDate: z.string().optional(),
    weeklyHours: z.string().min(1, 'Horas semanais são obrigatórias'),
    orgUnit: z.string().min(1, 'Unidade organizacional é obrigatória'),
    position: z.string().min(1, 'Cargo é obrigatório'),
    salaryCategory: z.string().min(1, 'Categoria salarial é obrigatória'),
    salaryGrade: z.string().min(1, 'Grau é obrigatório'),
    salaryStep: z.string().min(1, 'Escalão é obrigatório'),
    legalActReference: z.string().min(1, 'Referência legal é obrigatória'),
});

// Schema para conta bancária
const bankAccountSchema = z.object({
    bankId: z.string().optional(),
    accountNumber: z.string().optional(),
    iban: z.string().optional(),
    isPrimary: z.boolean().default(false),
    skipBankAccount: z.boolean().default(false),
});

type AgentFormData = z.infer<typeof agentSchema>;
type ContractFormData = z.infer<typeof contractSchema>;
type BankAccountFormData = z.infer<typeof bankAccountSchema>;

interface AgentWizardModalProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    onComplete?: () => void;
}

const STEPS = [
    { id: 1, title: 'Dados do Agente', icon: User },
    { id: 2, title: 'Contrato/Vínculo', icon: FileSignature },
    { id: 3, title: 'Conta Bancária', icon: CreditCard },
];

export function AgentWizardModal({ open, onOpenChange, onComplete }: AgentWizardModalProps) {
    const [currentStep, setCurrentStep] = useState(1);
    const [createdAgentId, setCreatedAgentId] = useState<string | null>(null);
    const [loading, setLoading] = useState(false);

    // Lookup data
    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 [banks, setBanks] = useState<BankDTO[]>([]);
    const [selectedCategory, setSelectedCategory] = useState("");
    const [selectedGrade, setSelectedGrade] = useState("");
    const [selectedOrgUnit, setSelectedOrgUnit] = useState("");

    // Forms
    const agentForm = useForm<AgentFormData>({
        resolver: zodResolver(agentSchema),
        defaultValues: {
            status: 'REGISTERED',
            eligibleDependentsCount: '0',
        },
    });

    const contractForm = useForm<ContractFormData>({
        resolver: zodResolver(contractSchema),
        mode: 'onChange',
        defaultValues: {
            contractType: '',
            startDate: '',
            endDate: '',
            weeklyHours: '40',
            orgUnit: '',
            position: '',
            salaryCategory: '',
            salaryGrade: '',
            salaryStep: '',
            legalActReference: '',
        },
    });

    const bankAccountForm = useForm<BankAccountFormData>({
        resolver: zodResolver(bankAccountSchema),
        defaultValues: {
            isPrimary: true,
            skipBankAccount: false,
        },
    });

    useEffect(() => {
        if (open) {
            loadLookupData();
            // Reset forms com valores padrão explícitos
            const agentDefaults: AgentFormData = {
                matricula: '',
                nif: '',
                biNumber: '',
                fullName: '',
                birthDate: '',
                hireDate: '',
                posseDate: '',
                status: 'REGISTERED',
                literaryQualification: '',
                eligibleDependentsCount: '0',
                nationality: '',
                email: '',
                phone: '',
                address: '',
                orgUnit: '',
                position: '',
                salaryCategory: '',
                salaryGrade: '',
                salaryStep: '',
            };
            const contractDefaults = {
                contractType: '',
                startDate: '',
                endDate: '',
                weeklyHours: '40',
                orgUnit: '',
                position: '',
                salaryCategory: '',
                salaryGrade: '',
                salaryStep: '',
                legalActReference: '',
            };
            const bankDefaults = {
                bankId: '',
                accountNumber: '',
                iban: '',
                isPrimary: true,
                skipBankAccount: false,
            };
            
            agentForm.reset(agentDefaults);
            contractForm.reset(contractDefaults);
            bankAccountForm.reset(bankDefaults);
            
            setCurrentStep(1);
            setCreatedAgentId(null);
            setSelectedCategory('');
            setSelectedGrade('');
            setSelectedOrgUnit('');
            setPositions([]);
            setGrades([]);
            setSteps([]);
        }
    }, [open]);

    // Garantir que o formulário de contrato seja resetado quando entrar na etapa 2
    useEffect(() => {
        if (currentStep === 2 && open) {
            // Forçar reset do formulário de contrato
            contractForm.reset({
                contractType: '',
                startDate: '',
                endDate: '',
                weeklyHours: '40',
                orgUnit: '',
                position: '',
                salaryCategory: '',
                salaryGrade: '',
                salaryStep: '',
                legalActReference: '',
            });
            // Garantir valores iniciais
            setTimeout(() => {
                contractForm.setValue('weeklyHours', '40', { shouldValidate: false });
                contractForm.setValue('contractType', '', { shouldValidate: false });
            }, 100);
        }
    }, [currentStep, open]);

    const loadLookupData = async () => {
        try {
            const [orgs, cats, banksData] = await Promise.all([
                orgService.getOrgUnits({ size: 100 }),
                salaryService.getAllCategories(),
                commonService.getBanks({ page: 0, size: 100 }),
            ]);
            setOrgUnits(orgs.content);
            setCategories(cats);
            setBanks(banksData.content);
        } catch (error) {
            console.error('Erro ao carregar dados', error);
        }
    };

    const handleOrgChange = async (orgId: string) => {
        setSelectedOrgUnit(orgId);
        // Limpa o cargo selecionado quando muda a unidade
        contractForm.setValue('position', '');
        if (!orgId) {
            setPositions([]);
            return;
        }
        try {
            const data = await orgService.getPositions({ orgUnitId: orgId });
            const positionsList = Array.isArray(data) ? data : [];
            setPositions(positionsList);
            if (positionsList.length === 0) {
                toast.info('Nenhum cargo encontrado para esta unidade organizacional');
            }
        } catch (error) {
            console.error('Erro ao carregar cargos', error);
            toast.error('Erro ao carregar cargos da unidade organizacional');
            setPositions([]);
        }
    };

    const handleCategoryChange = async (catId: string) => {
        setSelectedCategory(catId);
        setSelectedGrade("");
        setSteps([]);
        // Limpa os campos dependentes
        contractForm.setValue('salaryGrade', '');
        contractForm.setValue('salaryStep', '');
        if (!catId) {
            setGrades([]);
            return;
        }
        try {
            const data = await salaryService.getGradesByCategory(catId);
            setGrades(Array.isArray(data) ? data : []);
            if (Array.isArray(data) && data.length === 0) {
                toast.info('Nenhum grau encontrado para esta categoria');
            }
        } catch (error) {
            console.error('Erro ao carregar graus', error);
            toast.error('Erro ao carregar graus da categoria');
            setGrades([]);
        }
    };

    const handleGradeChange = async (gradeId: string) => {
        setSelectedGrade(gradeId);
        // Limpa o escalão quando muda o grau
        contractForm.setValue('salaryStep', '');
        if (!gradeId) {
            setSteps([]);
            return;
        }
        try {
            const data = await salaryService.getStepsByGrade(gradeId);
            setSteps(Array.isArray(data) ? data : []);
            if (Array.isArray(data) && data.length === 0) {
                toast.info('Nenhum escalão encontrado para este grau');
            }
        } catch (error) {
            console.error('Erro ao carregar escalões', error);
            toast.error('Erro ao carregar escalões do grau');
            setSteps([]);
        }
    };

    const handleAgentSubmit = async (data: AgentFormData) => {
        try {
            setLoading(true);
            const agentData = {
                ...data,
                eligibleDependentsCount: parseInt(data.eligibleDependentsCount || '0'),
            };
            const created = await rhService.createAgent(agentData);
            setCreatedAgentId(created.id);
            toast.success('Agente criado com sucesso!');
            
            // Garantir que o formulário de contrato está limpo antes de avançar
            contractForm.reset({
                contractType: '',
                startDate: '',
                endDate: '',
                weeklyHours: '40',
                orgUnit: '',
                position: '',
                salaryCategory: '',
                salaryGrade: '',
                salaryStep: '',
                legalActReference: '',
            });
            
            // Forçar valores iniciais
            contractForm.setValue('weeklyHours', '40', { shouldValidate: false, shouldDirty: false });
            contractForm.setValue('contractType', '', { shouldValidate: false, shouldDirty: false });
            
            setCurrentStep(2);
        } catch (error: any) {
            toast.error(error?.response?.data?.message || 'Erro ao criar agente');
        } finally {
            setLoading(false);
        }
    };

    const handleContractSubmit = async (data: ContractFormData) => {
        if (!createdAgentId) {
            toast.error('Agente não foi criado. Volte ao passo anterior.');
            return;
        }

        // Validação adicional
        if (!data.contractType || !data.startDate || !data.weeklyHours || !data.orgUnit || 
            !data.position || !data.salaryCategory || !data.salaryGrade || !data.salaryStep || 
            !data.legalActReference) {
            toast.error('Preencha todos os campos obrigatórios');
            return;
        }

        try {
            setLoading(true);
            const contractData = {
                agent: { id: createdAgentId },
                contractType: data.contractType,
                startDate: data.startDate,
                endDate: data.endDate && data.endDate.trim() !== '' ? data.endDate : null,
                weeklyHours: parseInt(data.weeklyHours) || 40,
                orgUnit: data.orgUnit,
                position: data.position,
                salaryCategory: data.salaryCategory,
                salaryGrade: data.salaryGrade,
                salaryStep: data.salaryStep,
                legalActReference: data.legalActReference,
                isActive: true,
            };
            await rhService.saveContract(contractData);
            toast.success('Contrato criado com sucesso!');
            setCurrentStep(3);
        } catch (error: any) {
            console.error('Erro ao criar contrato:', error);
            const errorMessage = error?.response?.data?.message || 
                                error?.response?.data?.error || 
                                error?.message || 
                                'Erro ao criar contrato';
            toast.error(errorMessage);
        } finally {
            setLoading(false);
        }
    };

    const handleBankAccountSubmit = async (data: BankAccountFormData) => {
        if (!createdAgentId) {
            toast.error('Agente não foi criado.');
            return;
        }

        if (data.skipBankAccount) {
            handleComplete();
            return;
        }

        if (!data.bankId || !data.accountNumber) {
            toast.error('Preencha os dados da conta bancária ou marque para pular');
            return;
        }

        try {
            setLoading(true);
            const selectedBank = banks.find(b => b.id === data.bankId);
            if (!selectedBank) {
                toast.error('Banco inválido');
                return;
            }

            const bankAccountData = {
                agent: { id: createdAgentId },
                bank: selectedBank.name,
                branchCode: selectedBank.code,
                accountNumber: data.accountNumber,
                iban: data.iban || undefined,
                isPrimary: data.isPrimary,
            };
            await rhService.saveBankAccount(bankAccountData);
            toast.success('Conta bancária vinculada com sucesso!');
            handleComplete();
        } catch (error: any) {
            toast.error(error?.response?.data?.message || 'Erro ao vincular conta bancária');
        } finally {
            setLoading(false);
        }
    };

    const handleComplete = () => {
        toast.success('Cadastro completo! Agente, contrato e conta bancária foram criados.');
        onComplete?.();
        onOpenChange(false);
    };

    const handleSkipContract = () => {
        // Pular o passo do contrato e ir direto para conta bancária
        toast.info('Passo do contrato pulado. Você pode cadastrar o contrato posteriormente.');
        setCurrentStep(3);
    };

    const handleNext = () => {
        if (currentStep === 1) {
            agentForm.handleSubmit(handleAgentSubmit)();
        } else if (currentStep === 2) {
            // Validar antes de submeter
            const contractData = contractForm.getValues();
            if (!contractData.contractType || !contractData.weeklyHours || !contractData.startDate) {
                toast.error('Preencha todos os campos obrigatórios');
                return;
            }
            contractForm.handleSubmit(handleContractSubmit)();
        }
    };

    const handleBack = () => {
        if (currentStep > 1) {
            setCurrentStep(currentStep - 1);
        }
    };

    const renderStepIndicator = () => (
        <div className="flex items-center justify-between mb-6">
            {STEPS.map((step, index) => {
                const Icon = step.icon;
                const isActive = currentStep === step.id;
                const isCompleted = currentStep > step.id;
                const isLast = index === STEPS.length - 1;

                return (
                    <div key={step.id} className="flex items-center flex-1">
                        <div className="flex flex-col items-center flex-1">
                            <div
                                className={`w-10 h-10 rounded-full flex items-center justify-center border-2 transition-colors ${
                                    isCompleted
                                        ? 'bg-primary border-primary text-white'
                                        : isActive
                                        ? 'bg-primary border-primary text-white'
                                        : 'bg-gray-100 border-gray-300 text-gray-400'
                                }`}
                            >
                                {isCompleted ? (
                                    <CheckCircle2 className="w-5 h-5" />
                                ) : (
                                    <Icon className="w-5 h-5" />
                                )}
                            </div>
                            <span
                                className={`mt-2 text-xs font-medium ${
                                    isActive ? 'text-primary' : 'text-gray-500'
                                }`}
                            >
                                {step.title}
                            </span>
                        </div>
                        {!isLast && (
                            <div
                                className={`flex-1 h-0.5 mx-2 ${
                                    isCompleted ? 'bg-primary' : 'bg-gray-200'
                                }`}
                            />
                        )}
                    </div>
                );
            })}
        </div>
    );

    const renderStepContent = () => {
        switch (currentStep) {
            case 1:
                return (
                    <Form {...agentForm}>
                        <form onSubmit={agentForm.handleSubmit(handleAgentSubmit)} className="space-y-4" key="agent-form-step-1">
                            <div className="grid grid-cols-2 gap-4">
                                <FormField
                                    control={agentForm.control}
                                    name="matricula"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>Matrícula *</FormLabel>
                                            <FormControl>
                                                <Input 
                                                    value={field.value || ''} 
                                                    onChange={(e) => field.onChange(e.target.value)}
                                                    onBlur={field.onBlur}
                                                    name="agent-matricula"
                                                    id="agent-matricula-input"
                                                    ref={field.ref}
                                                    placeholder="EX: 2024001" 
                                                />
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />
                                <FormField
                                    control={agentForm.control}
                                    name="nif"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>NIF *</FormLabel>
                                            <FormControl>
                                                <Input 
                                                    value={field.value || ''} 
                                                    onChange={(e) => field.onChange(e.target.value)}
                                                    onBlur={field.onBlur}
                                                    name="agent-nif"
                                                    id="agent-nif-input"
                                                    ref={field.ref}
                                                    placeholder="NIF" 
                                                />
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />
                            </div>

                            <FormField
                                control={agentForm.control}
                                name="fullName"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>Nome Completo *</FormLabel>
                                        <FormControl>
                                            <Input 
                                                value={field.value || ''} 
                                                onChange={(e) => field.onChange(e.target.value)}
                                                onBlur={field.onBlur}
                                                name={field.name}
                                                ref={field.ref}
                                                placeholder="Nome do funcionário" 
                                            />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />

                            <div className="grid grid-cols-2 gap-4">
                                <FormField
                                    control={agentForm.control}
                                    name="birthDate"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>Data de Nascimento *</FormLabel>
                                            <FormControl>
                                                <Input 
                                                    type="date" 
                                                    value={field.value || ''} 
                                                    onChange={(e) => field.onChange(e.target.value)}
                                                    onBlur={field.onBlur}
                                                    name={field.name}
                                                    ref={field.ref}
                                                />
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />
                                <FormField
                                    control={agentForm.control}
                                    name="hireDate"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>Data de Admissão *</FormLabel>
                                            <FormControl>
                                                <Input 
                                                    type="date" 
                                                    value={field.value || ''} 
                                                    onChange={(e) => field.onChange(e.target.value)}
                                                    onBlur={field.onBlur}
                                                    name={field.name}
                                                    ref={field.ref}
                                                />
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />
                            </div>

                            <div className="grid grid-cols-2 gap-4">
                                <FormField
                                    control={agentForm.control}
                                    name="posseDate"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>Data de Posse *</FormLabel>
                                            <FormControl>
                                                <Input 
                                                    type="date" 
                                                    value={field.value || ''} 
                                                    onChange={(e) => field.onChange(e.target.value)}
                                                    onBlur={field.onBlur}
                                                    name="agent-posseDate"
                                                    id="agent-posseDate-input"
                                                    ref={field.ref}
                                                    placeholder="Data de posse" 
                                                />
                                            </FormControl>
                                            <p className="text-xs text-muted-foreground mt-1">
                                                Data em que o funcionário assume efetivamente o cargo. Usada para cálculo de salário proporcional.
                                            </p>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />
                            </div>

                            <div className="grid grid-cols-2 gap-4">
                                <FormField
                                    control={agentForm.control}
                                    name="biNumber"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>Número de BI *</FormLabel>
                                            <FormControl>
                                                <Input 
                                                    value={field.value || ''} 
                                                    onChange={(e) => field.onChange(e.target.value)}
                                                    onBlur={field.onBlur}
                                                    name={field.name}
                                                    ref={field.ref}
                                                    placeholder="Número do BI" 
                                                />
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />
                                <FormField
                                    control={agentForm.control}
                                    name="eligibleDependentsCount"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>Nº Dependentes</FormLabel>
                                            <FormControl>
                                                <Input 
                                                    type="number" 
                                                    min="0" 
                                                    max="3" 
                                                    value={field.value || '0'} 
                                                    onChange={(e) => field.onChange(e.target.value)}
                                                    onBlur={field.onBlur}
                                                    name={field.name}
                                                    ref={field.ref}
                                                    placeholder="0-3" 
                                                />
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />
                            </div>

                            <div className="grid grid-cols-2 gap-4">
                                <FormField
                                    control={agentForm.control}
                                    name="email"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>Email</FormLabel>
                                            <FormControl>
                                                <Input 
                                                    type="email" 
                                                    value={field.value || ''} 
                                                    onChange={(e) => field.onChange(e.target.value)}
                                                    onBlur={field.onBlur}
                                                    name={field.name}
                                                    ref={field.ref}
                                                    placeholder="email@exemplo.com" 
                                                />
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />
                                <FormField
                                    control={agentForm.control}
                                    name="phone"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>Telefone</FormLabel>
                                            <FormControl>
                                                <Input 
                                                    value={field.value || ''} 
                                                    onChange={(e) => field.onChange(e.target.value)}
                                                    onBlur={field.onBlur}
                                                    name={field.name}
                                                    ref={field.ref}
                                                    placeholder="+245..." 
                                                />
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />
                            </div>

                            <FormField
                                control={agentForm.control}
                                name="address"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>Endereço</FormLabel>
                                        <FormControl>
                                            <Textarea 
                                                value={field.value || ''} 
                                                onChange={(e) => field.onChange(e.target.value)}
                                                onBlur={field.onBlur}
                                                name={field.name}
                                                ref={field.ref}
                                                placeholder="Endereço residencial" 
                                            />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />
                        </form>
                    </Form>
                );

            case 2:
                // Verificar discrepância entre data de posse e data de início do contrato
                const posseDate = agentForm.watch('posseDate');
                const contractStartDate = contractForm.watch('startDate');
                let dateDiscrepancyWarning = null;
                
                if (posseDate && contractStartDate) {
                    const posse = new Date(posseDate);
                    const start = new Date(contractStartDate);
                    const diffDays = Math.abs((posse.getTime() - start.getTime()) / (1000 * 60 * 60 * 24));
                    
                    // Aviso se a diferença for maior que 30 dias
                    if (diffDays > 30) {
                        const isPosseAfter = posse > start;
                        dateDiscrepancyWarning = (
                            <Alert className="mb-4 border-yellow-500 bg-yellow-50 dark:bg-yellow-900/20">
                                <AlertDescription className="text-yellow-800 dark:text-yellow-200">
                                    <strong>Atenção:</strong> Há uma diferença significativa ({Math.round(diffDays)} dias) entre a Data de Posse ({new Date(posseDate).toLocaleDateString('pt-BR')}) e a Data de Início do Contrato ({new Date(contractStartDate).toLocaleDateString('pt-BR')}).
                                    {isPosseAfter 
                                        ? ' A data de posse é posterior à data do contrato, o que pode indicar regularização ou caso retroativo.'
                                        : ' A data do contrato é posterior à data de posse, o que pode indicar regularização ou caso retroativo.'
                                    }
                                    {' '}Verifique se as datas estão corretas conforme o Decreto 12-A/94.
                                </AlertDescription>
                            </Alert>
                        );
                    }
                }
                
                return (
                    <Form {...contractForm}>
                        <form onSubmit={contractForm.handleSubmit(handleContractSubmit)} className="space-y-4" key="contract-form">
                            {dateDiscrepancyWarning}
                            
                            <div className="mb-4 p-3 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg">
                                <p className="text-sm text-blue-800 dark:text-blue-200">
                                    <strong>Nota:</strong> O contrato é opcional. Você pode pular este passo e cadastrar o contrato posteriormente. 
                                    A Data de Posse já foi registrada no cadastro do agente e será usada para cálculo de salário.
                                </p>
                            </div>
                            
                            <div className="grid grid-cols-2 gap-4">
                                <FormField
                                    control={contractForm.control}
                                    name="contractType"
                                    render={({ field }) => {
                                        // Usar watch para obter o valor atual do formulário
                                        const watchedValue = contractForm.watch('contractType');
                                        const selectValue = watchedValue && watchedValue.trim() !== '' ? watchedValue : '';
                                        
                                        return (
                                            <FormItem>
                                                <FormLabel>Tipo de Contrato *</FormLabel>
                                                <Select 
                                                    onValueChange={(value) => {
                                                        console.log('[contractType] Selected:', value);
                                                        field.onChange(value);
                                                        contractForm.setValue('contractType', value, { shouldValidate: true, shouldDirty: true });
                                                    }} 
                                                    value={selectValue || undefined}
                                                >
                                                    <FormControl>
                                                        <SelectTrigger>
                                                            <SelectValue placeholder="Selecione o tipo de contrato..." />
                                                        </SelectTrigger>
                                                    </FormControl>
                                                    <SelectContent>
                                                        <SelectItem value="NOMEAÇÃO_DEFINITIVA">Nomeação Definitiva</SelectItem>
                                                        <SelectItem value="NOMEAÇÃO_PROVISORIA">Nomeação Provisória</SelectItem>
                                                        <SelectItem value="CONTRATO_TERMO">Contrato a Termo</SelectItem>
                                                        <SelectItem value="CONTRATO_PRESTAÇÃO_SERVIÇOS">Prestação de Serviços</SelectItem>
                                                    </SelectContent>
                                                </Select>
                                                <FormMessage />
                                            </FormItem>
                                        );
                                    }}
                                />
                                <FormField
                                    control={contractForm.control}
                                    name="weeklyHours"
                                    render={({ field }) => {
                                        // Sempre garantir que o valor seja '40' se estiver vazio ou inválido
                                        const currentValue = contractForm.getValues('weeklyHours');
                                        let safeValue = '40';
                                        
                                        if (currentValue && typeof currentValue === 'string' && /^\d+$/.test(currentValue)) {
                                            safeValue = currentValue;
                                        } else if (currentValue && !isNaN(Number(currentValue))) {
                                            safeValue = String(Math.max(1, Math.min(168, Math.floor(Number(currentValue)))));
                                        }
                                        
                                        // Se o valor atual não for seguro, atualizar
                                        if (field.value !== safeValue && (field.value === '' || !field.value || isNaN(Number(field.value)))) {
                                            // Usar requestAnimationFrame para evitar conflitos
                                            requestAnimationFrame(() => {
                                                contractForm.setValue('weeklyHours', safeValue, { shouldValidate: false });
                                            });
                                        }
                                        
                                        return (
                                            <FormItem>
                                                <FormLabel>Horas Semanais *</FormLabel>
                                                <FormControl>
                                                    <Input 
                                                        type="number" 
                                                        min="1"
                                                        max="168"
                                                        step="1"
                                                        value={safeValue} 
                                                        onChange={(e) => {
                                                            const val = e.target.value;
                                                            // Apenas aceitar números válidos
                                                            if (val === '' || /^\d+$/.test(val)) {
                                                                const numVal = val === '' ? 40 : parseInt(val, 10);
                                                                const clampedVal = Math.max(1, Math.min(168, numVal));
                                                                field.onChange(String(clampedVal));
                                                            }
                                                        }}
                                                        onBlur={(e) => {
                                                            const val = e.target.value;
                                                            if (!val || val === '' || isNaN(Number(val))) {
                                                                field.onChange('40');
                                                            }
                                                            field.onBlur();
                                                        }}
                                                        name="contract-weeklyHours"
                                                        id="contract-weeklyHours-input"
                                                        ref={field.ref}
                                                        placeholder="Ex: 40" 
                                                        autoComplete="off"
                                                    />
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        );
                                    }}
                                />
                            </div>

                            <FormField
                                control={contractForm.control}
                                name="legalActReference"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>Referência Legal (Ato) *</FormLabel>
                                        <FormControl>
                                            <Input 
                                                value={field.value || ''} 
                                                onChange={(e) => field.onChange(e.target.value)}
                                                onBlur={field.onBlur}
                                                name={field.name}
                                                ref={field.ref}
                                                placeholder="Ex: Decreto nº 12/2023, Despacho nº 45..." 
                                            />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />

                            <FormField
                                control={contractForm.control}
                                name="orgUnit"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>Unidade Organizacional *</FormLabel>
                                        <Select
                                            onValueChange={(value) => {
                                                field.onChange(value);
                                                handleOrgChange(value);
                                            }}
                                            value={field.value || ""}
                                        >
                                            <FormControl>
                                                <SelectTrigger>
                                                    <SelectValue placeholder="Selecione..." />
                                                </SelectTrigger>
                                            </FormControl>
                                            <SelectContent>
                                                {orgUnits.map(unit => (
                                                    <SelectItem key={unit.id} value={unit.id}>
                                                        {unit.name}
                                                    </SelectItem>
                                                ))}
                                            </SelectContent>
                                        </Select>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />

                            <FormField
                                control={contractForm.control}
                                name="position"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>Cargo/Função *</FormLabel>
                                        <Select 
                                            onValueChange={field.onChange} 
                                            value={field.value || ""}
                                            disabled={!selectedOrgUnit || positions.length === 0}
                                        >
                                            <FormControl>
                                                <SelectTrigger>
                                                    <SelectValue placeholder={
                                                        !selectedOrgUnit 
                                                            ? "Selecione primeiro a unidade organizacional" 
                                                            : positions.length === 0 
                                                            ? "Nenhum cargo disponível nesta unidade"
                                                            : "Selecione o cargo..."
                                                    } />
                                                </SelectTrigger>
                                            </FormControl>
                                            <SelectContent>
                                                {positions.length === 0 ? (
                                                    <SelectItem value="__empty__" disabled>
                                                        {!selectedOrgUnit 
                                                            ? "Selecione primeiro a unidade organizacional" 
                                                            : "Nenhum cargo disponível nesta unidade"}
                                                    </SelectItem>
                                                ) : (
                                                    positions.map(pos => (
                                                        <SelectItem key={pos.id} value={pos.id}>
                                                            {pos.title}
                                                        </SelectItem>
                                                    ))
                                                )}
                                            </SelectContent>
                                        </Select>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />

                            <FormField
                                control={contractForm.control}
                                name="salaryCategory"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>Categoria Salarial *</FormLabel>
                                        <Select
                                            onValueChange={(value) => {
                                                field.onChange(value);
                                                handleCategoryChange(value);
                                            }}
                                            value={field.value || ""}
                                        >
                                            <FormControl>
                                                <SelectTrigger>
                                                    <SelectValue placeholder="Selecione..." />
                                                </SelectTrigger>
                                            </FormControl>
                                            <SelectContent>
                                                {categories.map(cat => (
                                                    <SelectItem key={cat.id} value={cat.id}>
                                                        {cat.name}
                                                    </SelectItem>
                                                ))}
                                            </SelectContent>
                                        </Select>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />

                            <div className="grid grid-cols-2 gap-4">
                                <FormField
                                    control={contractForm.control}
                                    name="salaryGrade"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>Grau *</FormLabel>
                                            <Select
                                                onValueChange={(value) => {
                                                    field.onChange(value);
                                                    handleGradeChange(value);
                                                }}
                                                value={field.value || ""}
                                                disabled={!selectedCategory || grades.length === 0}
                                            >
                                                <FormControl>
                                                    <SelectTrigger>
                                                        <SelectValue placeholder={
                                                            !selectedCategory 
                                                                ? "Selecione primeiro a categoria salarial" 
                                                                : grades.length === 0 
                                                                ? "Nenhum grau disponível nesta categoria"
                                                                : "Selecione o grau..."
                                                        } />
                                                    </SelectTrigger>
                                                </FormControl>
                                                <SelectContent>
                                                    {grades.length === 0 ? (
                                                        <SelectItem value="__empty__" disabled>
                                                            {!selectedCategory 
                                                                ? "Selecione primeiro a categoria salarial" 
                                                                : "Nenhum grau disponível nesta categoria"}
                                                        </SelectItem>
                                                    ) : (
                                                        grades.map(grade => (
                                                            <SelectItem key={grade.id} value={grade.id}>
                                                                {grade.name}
                                                            </SelectItem>
                                                        ))
                                                    )}
                                                </SelectContent>
                                            </Select>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />
                                <FormField
                                    control={contractForm.control}
                                    name="salaryStep"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>Escalão *</FormLabel>
                                            <Select 
                                                onValueChange={field.onChange} 
                                                value={field.value || ""}
                                                disabled={!selectedGrade || steps.length === 0}
                                            >
                                                <FormControl>
                                                    <SelectTrigger>
                                                        <SelectValue placeholder={
                                                            !selectedGrade 
                                                                ? "Selecione primeiro o grau" 
                                                                : steps.length === 0 
                                                                ? "Nenhum escalão disponível neste grau"
                                                                : "Selecione o escalão..."
                                                        } />
                                                    </SelectTrigger>
                                                </FormControl>
                                                <SelectContent>
                                                    {steps.length === 0 ? (
                                                        <SelectItem value="__empty__" disabled>
                                                            {!selectedGrade 
                                                                ? "Selecione primeiro o grau" 
                                                                : "Nenhum escalão disponível neste grau"}
                                                        </SelectItem>
                                                    ) : (
                                                        steps.map(step => (
                                                            <SelectItem key={step.id} value={step.id}>
                                                                Escalão {step.stepNumber}
                                                            </SelectItem>
                                                        ))
                                                    )}
                                                </SelectContent>
                                            </Select>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />
                            </div>

                            <div className="grid grid-cols-2 gap-4">
                                <FormField
                                    control={contractForm.control}
                                    name="startDate"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>Data Início *</FormLabel>
                                            <FormControl>
                                                <Input 
                                                    type="date" 
                                                    value={field.value || ''} 
                                                    onChange={(e) => field.onChange(e.target.value)}
                                                    onBlur={field.onBlur}
                                                    name={field.name}
                                                    ref={field.ref}
                                                />
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />
                                <FormField
                                    control={contractForm.control}
                                    name="endDate"
                                    render={({ field }) => (
                                        <FormItem>
                                            <FormLabel>Data Fim (Opcional)</FormLabel>
                                            <FormControl>
                                                <Input 
                                                    type="date" 
                                                    value={field.value || ''} 
                                                    onChange={(e) => field.onChange(e.target.value)}
                                                    onBlur={field.onBlur}
                                                    name={field.name}
                                                    ref={field.ref}
                                                />
                                            </FormControl>
                                            <FormMessage />
                                        </FormItem>
                                    )}
                                />
                            </div>
                            
                            <div className="flex justify-between items-center pt-4 border-t mt-4">
                                <Button
                                    type="button"
                                    variant="outline"
                                    onClick={handleSkipContract}
                                    disabled={loading}
                                >
                                    Pular este passo
                                </Button>
                                <p className="text-sm text-muted-foreground">
                                    O contrato pode ser cadastrado posteriormente. A Data de Posse já foi registrada.
                                </p>
                            </div>
                        </form>
                    </Form>
                );

            case 3:
                return (
                    <Form {...bankAccountForm}>
                        <form onSubmit={bankAccountForm.handleSubmit(handleBankAccountSubmit)} className="space-y-4">
                            <FormField
                                control={bankAccountForm.control}
                                name="skipBankAccount"
                                render={({ field }) => (
                                    <FormItem className="flex flex-row items-start space-x-3 space-y-0 rounded-md border p-4">
                                        <FormControl>
                                            <Checkbox
                                                checked={field.value}
                                                onCheckedChange={field.onChange}
                                            />
                                        </FormControl>
                                        <div className="space-y-1 leading-none">
                                            <FormLabel>
                                                Pular este passo (cadastrar conta bancária depois)
                                            </FormLabel>
                                        </div>
                                    </FormItem>
                                )}
                            />

                            {!bankAccountForm.watch('skipBankAccount') && (
                                <>
                                    <FormField
                                        control={bankAccountForm.control}
                                        name="bankId"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel>Banco</FormLabel>
                                                <Select onValueChange={field.onChange} value={field.value || ""}>
                                                    <FormControl>
                                                        <SelectTrigger>
                                                            <SelectValue placeholder="Selecione o banco..." />
                                                        </SelectTrigger>
                                                    </FormControl>
                                                    <SelectContent>
                                                        {banks.map(bank => (
                                                            <SelectItem key={bank.id} value={bank.id}>
                                                                {bank.name}
                                                            </SelectItem>
                                                        ))}
                                                    </SelectContent>
                                                </Select>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />

                                    <FormField
                                        control={bankAccountForm.control}
                                        name="accountNumber"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel>Número da Conta</FormLabel>
                                                <FormControl>
                                                    <Input 
                                                        value={field.value || ''} 
                                                        onChange={(e) => field.onChange(e.target.value)}
                                                        onBlur={field.onBlur}
                                                        name={field.name}
                                                        ref={field.ref}
                                                        placeholder="Número da Conta" 
                                                    />
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />

                                    <FormField
                                        control={bankAccountForm.control}
                                        name="iban"
                                        render={({ field }) => (
                                            <FormItem>
                                                <FormLabel>IBAN (Opcional)</FormLabel>
                                                <FormControl>
                                                    <Input 
                                                        value={field.value || ''} 
                                                        onChange={(e) => field.onChange(e.target.value)}
                                                        onBlur={field.onBlur}
                                                        name={field.name}
                                                        ref={field.ref}
                                                        placeholder="GW00 0000 0000 0000 0000 00" 
                                                        className="font-mono" 
                                                    />
                                                </FormControl>
                                                <FormMessage />
                                            </FormItem>
                                        )}
                                    />

                                    <FormField
                                        control={bankAccountForm.control}
                                        name="isPrimary"
                                        render={({ field }) => (
                                            <FormItem className="flex flex-row items-start space-x-3 space-y-0 rounded-md border p-4">
                                                <FormControl>
                                                    <Checkbox
                                                        checked={field.value}
                                                        onCheckedChange={field.onChange}
                                                    />
                                                </FormControl>
                                                <div className="space-y-1 leading-none">
                                                    <FormLabel>
                                                        Conta principal para pagamentos
                                                    </FormLabel>
                                                </div>
                                            </FormItem>
                                        )}
                                    />
                                </>
                            )}
                        </form>
                    </Form>
                );

            default:
                return null;
        }
    };

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="sm:max-w-4xl max-h-[90vh] overflow-y-auto">
                <DialogHeader>
                    <DialogTitle>Cadastro Completo de Agente</DialogTitle>
                    <DialogDescription>
                        Preencha os dados do agente, contrato e conta bancária em um único fluxo
                    </DialogDescription>
                </DialogHeader>

                {renderStepIndicator()}

                <div className="min-h-[400px]" key={`step-content-${currentStep}`}>
                    {renderStepContent()}
                </div>

                <div className="flex justify-between pt-4 border-t">
                    <Button
                        type="button"
                        variant="outline"
                        onClick={currentStep === 1 ? () => onOpenChange(false) : handleBack}
                        disabled={loading}
                    >
                        <ChevronLeft className="w-4 h-4 mr-2" />
                        {currentStep === 1 ? 'Cancelar' : 'Voltar'}
                    </Button>

                    <Button
                        type="button"
                        onClick={
                            currentStep === 3
                                ? bankAccountForm.handleSubmit(handleBankAccountSubmit)
                                : handleNext
                        }
                        disabled={loading}
                    >
                        {loading ? (
                            'Processando...'
                        ) : currentStep === 3 ? (
                            <>
                                Finalizar
                                <CheckCircle2 className="w-4 h-4 ml-2" />
                            </>
                        ) : (
                            <>
                                Próximo
                                <ChevronRight className="w-4 h-4 ml-2" />
                            </>
                        )}
                    </Button>
                </div>
            </DialogContent>
        </Dialog>
    );
}

