import { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    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 { AgentDTO } from '@/types/rh';
import { salaryService } from '@/services/salaryService';

const agentSchema = z.object({
    matricula: z.string().min(1, 'Matrícula é obrigatória').max(20),
    nif: z.string()
        .min(9, 'NIF deve ter pelo menos 9 dígitos')
        .max(20),
    biNumber: z.string()
        .min(1, 'Número do BI é obrigatório')
        .max(20),
    fullName: z.string().min(3, 'Nome deve ter no mínimo 3 caracteres').max(200),
    birthDate: z.string().min(1, 'Data de nascimento é obrigatória'),
    hireDate: z.string().min(1, 'Data de admissão é obrigatória'),
    posseDate: z.string().optional().or(z.literal('')),
    status: z.string().min(1, 'Status é obrigatório'),
    statusChangeReason: z.string().optional(),
    literaryQualification: z.string().optional(),
    eligibleDependentsCount: z.string().optional().or(z.literal('')),
    nationality: z.string().optional(),
    email: z.string().email('Email inválido').optional().or(z.literal('')),
    phone: z.string()
        .regex(/^(\+245)?\s?[9][567]\d{7}$|^(\+245)?\s?[2]\d{7}$/, 'Telefone inválido para Guiné-Bissau (Ex: +245 95XXXXXXX)')
        .optional().or(z.literal('')),
    address: z.string().optional(),

    // Novos campos para Vida Laboral
    eventEffectiveDate: z.string().optional().or(z.literal('')),
    eventPublicationDate: z.string().optional().or(z.literal('')),
    eventDocumentRef: z.string().optional(),
});

type AgentFormData = z.infer<typeof agentSchema>;

interface AgentFormModalProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    agent?: AgentDTO | null;
    onSubmit: (data: AgentFormData) => Promise<void>;
}

export function AgentFormModal({ open, onOpenChange, agent, onSubmit }: AgentFormModalProps) {
    const [showReason, setShowReason] = useState(false);
    const [isEditMode, setIsEditMode] = useState(false);

    const form = useForm<AgentFormData>({
        resolver: zodResolver(agentSchema),
        defaultValues: {
            matricula: '',
            nif: '',
            biNumber: '',
            fullName: '',
            birthDate: '',
            hireDate: '',
            posseDate: '',
            status: 'REGISTERED',
            statusChangeReason: '',
            literaryQualification: '',
            eligibleDependentsCount: '0',
            nationality: '',
            email: '',
            phone: '',
            address: '',
            eventEffectiveDate: '',
            eventPublicationDate: '',
            eventDocumentRef: '',
        },
    });

    useEffect(() => {
        if (agent && open) {
            form.reset({
                matricula: agent.matricula,
                nif: agent.nif,
                biNumber: agent.biNumber,
                fullName: agent.fullName,
                birthDate: agent.birthDate,
                hireDate: agent.hireDate,
                posseDate: agent.posseDate || '',
                status: agent.status,
                statusChangeReason: '',
                literaryQualification: agent.literaryQualification || '',
                eligibleDependentsCount: agent.eligibleDependentsCount?.toString() || '0',
                nationality: agent.nationality || '',
                email: agent.email || '',
                phone: agent.phone || '',
                address: agent.address || '',
                eventEffectiveDate: '',
                eventPublicationDate: '',
                eventDocumentRef: '',
            });
        } else if (open) {
            form.reset({
                matricula: '',
                nif: '',
                biNumber: '',
                fullName: '',
                birthDate: '',
                hireDate: '',
                posseDate: '',
                status: 'REGISTERED',
                statusChangeReason: '',
                literaryQualification: '',
                eligibleDependentsCount: '0',
                nationality: '',
                email: '',
                phone: '',
                address: '',
                eventEffectiveDate: '',
                eventPublicationDate: '',
                eventDocumentRef: '',
            });
        }
        setShowReason(false);
        setIsEditMode(!!agent);
    }, [agent, open, form]);

    const handleSubmit = async (data: AgentFormData) => {
        try {
            const submitData = { ...data };
            if (!submitData.nationality) delete submitData.nationality;
            if (!submitData.email) delete (submitData as any).email;
            if (!submitData.phone) delete (submitData as any).phone;
            if (!submitData.address) delete (submitData as any).address;
            if (!submitData.posseDate) delete submitData.posseDate;
            if (!submitData.literaryQualification) delete submitData.literaryQualification;
            if (!submitData.eventEffectiveDate) delete (submitData as any).eventEffectiveDate;
            if (!submitData.eventPublicationDate) delete (submitData as any).eventPublicationDate;
            if (!submitData.eventDocumentRef) delete (submitData as any).eventDocumentRef;

            const payload = {
                ...submitData,
                eligibleDependentsCount: submitData.eligibleDependentsCount ? parseInt(submitData.eligibleDependentsCount) : undefined
            };

            await onSubmit(payload as any);
        } catch (error) {
            console.error('Error submitting agent form:', error);
        }
    };

    const renderForm = () => (
        <Form {...form}>
            <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-4">
                <div className="grid grid-cols-2 gap-4">
                    <FormField
                        control={form.control}
                        name="matricula"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>Matrícula</FormLabel>
                                <FormControl>
                                    <Input placeholder="EX: 2024001" {...field} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />
                    <FormField
                        control={form.control}
                        name="nif"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>NIF</FormLabel>
                                <FormControl>
                                    <Input placeholder="NIF" {...field} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />
                    <FormField
                        control={form.control}
                        name="biNumber"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>Nº Bilhete de Identidade (BI)</FormLabel>
                                <FormControl>
                                    <Input placeholder="Número do BI" {...field} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />
                </div>

                <FormField
                    control={form.control}
                    name="fullName"
                    render={({ field }) => (
                        <FormItem>
                            <FormLabel>Nome Completo</FormLabel>
                            <FormControl>
                                <Input placeholder="Nome do funcionário" {...field} />
                            </FormControl>
                            <FormMessage />
                        </FormItem>
                    )}
                />

                <div className="grid grid-cols-2 gap-4">
                    <FormField
                        control={form.control}
                        name="birthDate"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>Data de Nascimento</FormLabel>
                                <FormControl>
                                    <Input type="date" {...field} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />
                    <FormField
                        control={form.control}
                        name="nationality"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>Nacionalidade</FormLabel>
                                <FormControl>
                                    <Input placeholder="Guineense" {...field} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />
                </div>

                <div className="grid grid-cols-2 gap-4">
                    <FormField
                        control={form.control}
                        name="email"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>Email</FormLabel>
                                <FormControl>
                                    <Input type="email" placeholder="email@exemplo.com" {...field} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />
                    <FormField
                        control={form.control}
                        name="phone"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>Telefone</FormLabel>
                                <FormControl>
                                    <Input placeholder="+245..." {...field} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />
                </div>

                <FormField
                    control={form.control}
                    name="address"
                    render={({ field }) => (
                        <FormItem>
                            <FormLabel>Endereço</FormLabel>
                            <FormControl>
                                <Input placeholder="Endereço residencial" {...field} />
                            </FormControl>
                            <FormMessage />
                        </FormItem>
                    )}
                />

                <div className="grid grid-cols-2 gap-4">
                    <FormField
                        control={form.control}
                        name="hireDate"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>Data de Admissão</FormLabel>
                                <FormControl>
                                    <Input type="date" {...field} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />
                    <FormField
                        control={form.control}
                        name="posseDate"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>Data de Posse</FormLabel>
                                <FormControl>
                                    <Input type="date" {...field} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />
                </div>

                <div className="grid grid-cols-2 gap-4">
                    <FormField
                        control={form.control}
                        name="literaryQualification"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>Habilitação Literária</FormLabel>
                                <Select onValueChange={field.onChange} defaultValue={field.value} value={field.value}>
                                    <FormControl>
                                        <SelectTrigger>
                                            <SelectValue placeholder="Selecione o nível" />
                                        </SelectTrigger>
                                    </FormControl>
                                    <SelectContent>
                                        <SelectItem value="ENSINO_BASICO">Ensino Básico</SelectItem>
                                        <SelectItem value="ENSINO_SECUNDARIO">Ensino Secundário</SelectItem>
                                        <SelectItem value="BACHARELATO">Bacharelato</SelectItem>
                                        <SelectItem value="LICENCIATURA">Licenciatura</SelectItem>
                                        <SelectItem value="MESTRADO">Mestrado</SelectItem>
                                        <SelectItem value="DOUTORAMENTO">Doutoramento</SelectItem>
                                    </SelectContent>
                                </Select>
                                <FormMessage />
                            </FormItem>
                        )}
                    />
                    <FormField
                        control={form.control}
                        name="eligibleDependentsCount"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>Nº Filhos (Abono de Família)</FormLabel>
                                <FormControl>
                                    <Input type="number" min="0" max="3" placeholder="0-3" {...field} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />
                </div>

                <div className="grid grid-cols-2 gap-4">
                    <FormField
                        control={form.control}
                        name="status"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>Status Administrativo</FormLabel>
                                <Select onValueChange={field.onChange} defaultValue={field.value} value={field.value} disabled={!isEditMode}>
                                    <FormControl>
                                        <SelectTrigger>
                                            <SelectValue placeholder="Selecione" />
                                        </SelectTrigger>
                                    </FormControl>
                                    <SelectContent>
                                        <SelectItem value="REGISTERED">Registado (Cadastro)</SelectItem>
                                        <SelectItem value="ACTIVE">Ativo (Com Vínculo)</SelectItem>
                                        <SelectItem value="INACTIVE">Inativo</SelectItem>
                                        <SelectItem value="SUSPENDED">Suspenso</SelectItem>
                                        <SelectItem value="TERMINATED">Desligado</SelectItem>
                                    </SelectContent>
                                </Select>
                                <FormMessage />
                            </FormItem>
                        )}
                    />
                </div>

                {isEditMode && (
                    <div className="space-y-4 border-t pt-4 mt-4 bg-blue-50/30 p-4 rounded-lg border-blue-100">
                        <div className="flex items-center gap-2 mb-2">
                            <h3 className="text-sm font-bold text-blue-900">Documentação Legal do Evento</h3>
                            <span className="text-[10px] bg-blue-200 text-blue-800 px-2 py-0.5 rounded-full uppercase font-bold">Obrigatório para Auditoria</span>
                        </div>
                        <div className="grid grid-cols-2 gap-4">
                            <FormField
                                control={form.control}
                                name="eventDocumentRef"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel className="text-blue-900">Nº do Despacho / Portaria / B.O.</FormLabel>
                                        <FormControl>
                                            <Input placeholder="Ex: Despacho nº 123/2024" {...field} className="border-blue-200 focus:ring-blue-500" />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />
                            <FormField
                                control={form.control}
                                name="eventEffectiveDate"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel className="text-blue-900">Data de Produção de Efeitos</FormLabel>
                                        <FormControl>
                                            <Input type="date" {...field} className="border-blue-200 focus:ring-blue-500" />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />
                        </div>
                        <FormField
                            control={form.control}
                            name="eventPublicationDate"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel className="text-blue-900">Data de Publicação (Opcional)</FormLabel>
                                    <FormControl>
                                        <Input type="date" {...field} className="border-blue-200 focus:ring-blue-500" />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />
                    </div>
                )}

                <DialogFooter className="mt-4">
                    <Button
                        type="button"
                        variant="outline"
                        onClick={() => onOpenChange(false)}
                    >
                        Cancelar
                    </Button>
                    <Button type="submit" disabled={form.formState.isSubmitting}>
                        {form.formState.isSubmitting
                            ? 'A guardar...'
                            : agent
                                ? 'Atualizar'
                                : 'Criar'}
                    </Button>
                </DialogFooter>
            </form>
        </Form>
    );

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="sm:max-w-[700px] max-h-[90vh] overflow-y-auto">
                <DialogHeader>
                    <DialogTitle>{agent ? 'Editar Agente' : 'Novo Agente'}</DialogTitle>
                    <DialogDescription>
                        {agent
                            ? 'Atualize as informações do funcionário'
                            : 'Preencha os dados para cadastrar um novo funcionário'}
                    </DialogDescription>
                </DialogHeader>

                {renderForm()}
            </DialogContent>
        </Dialog>
    );
}
