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 { OrgUnitDTO, MinistryDTO } from '@/types/org';
import { useMinistries } from '@/hooks/useMinistries';
import { useOrgUnits } from '@/hooks/useOrgUnits';

const orgUnitSchema = z.object({
    code: z.string().min(1, 'Código é obrigatório').max(20, 'Código deve ter no máximo 20 caracteres'),
    name: z.string().min(1, 'Nome é obrigatório').max(100, 'Nome deve ter no máximo 100 caracteres'),
    acronym: z.string().min(1, 'Sigla é obrigatória').max(20, 'Sigla deve ter no máximo 20 caracteres'),
    type: z.enum(['MINISTRY', 'SECRETARIAT', 'DIRECTORATE', 'DEPARTMENT', 'SECTION', 'OTHER'], {
        required_error: "Tipo é obrigatório",
    }),
    ministryId: z.string().min(1, 'Ministério é obrigatório'),
    parentUnitId: z.string().optional(),
    address: 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('')),
});

type OrgUnitFormData = z.infer<typeof orgUnitSchema>;

interface OrgUnitFormModalProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    orgUnit?: OrgUnitDTO | null;
    onSubmit: (data: OrgUnitFormData) => Promise<void>;
}

export function OrgUnitFormModal({ open, onOpenChange, orgUnit, onSubmit }: OrgUnitFormModalProps) {
    const { ministries } = useMinistries({ size: 100 }); // Fetch all ministries for select
    // For parent unit, we might need to fetch org units based on selected ministry, but for now let's fetch all or just text input?
    // Ideally it should be a select filtered by ministry. Let's use useOrgUnits but maybe we need a way to search.
    // For simplicity, let's load all org units for the parent select if ministry is selected.

    const form = useForm<OrgUnitFormData>({
        resolver: zodResolver(orgUnitSchema),
        defaultValues: {
            code: '',
            name: '',
            acronym: '',
            type: 'DIRECTORATE',
            ministryId: '',
            parentUnitId: '',
            address: '',
            email: '',
            phone: '',
        },
    });

    const selectedMinistryId = form.watch('ministryId');
    const { orgUnits: parentCandidates } = useOrgUnits({
        ministryId: selectedMinistryId,
        size: 100,
        autoFetch: !!selectedMinistryId
    });

    useEffect(() => {
        if (orgUnit) {
            form.reset({
                code: orgUnit.code,
                name: orgUnit.name,
                acronym: orgUnit.acronym,
                type: orgUnit.type,
                ministryId: orgUnit.ministryId,
                parentUnitId: orgUnit.parentUnitId || '',
                address: orgUnit.address || '',
                email: orgUnit.email || '',
                phone: orgUnit.phone || '',
            });
        } else {
            form.reset({
                code: '',
                name: '',
                acronym: '',
                type: 'DIRECTORATE',
                ministryId: '',
                parentUnitId: '',
                address: '',
                email: '',
                phone: '',
            });
        }
    }, [orgUnit, open, form]);

    const handleSubmit = async (data: OrgUnitFormData) => {
        // Clean up empty strings for optional fields
        const submitData = { ...data };
        if (submitData.parentUnitId === 'none' || !submitData.parentUnitId) {
            delete submitData.parentUnitId;
        }
        if (!submitData.address) delete submitData.address;
        if (!submitData.email) delete submitData.email;
        if (!submitData.phone) delete submitData.phone;

        await onSubmit(submitData);
    };

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="sm:max-w-[600px] max-h-[90vh] overflow-y-auto">
                <DialogHeader>
                    <DialogTitle>{orgUnit ? 'Editar Unidade Orgânica' : 'Nova Unidade Orgânica'}</DialogTitle>
                    <DialogDescription>
                        {orgUnit
                            ? 'Atualize as informações da unidade orgânica'
                            : 'Preencha os dados para criar uma nova unidade orgânica'}
                    </DialogDescription>
                </DialogHeader>

                <Form {...form}>
                    <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-4">
                        <div className="grid grid-cols-2 gap-4">
                            <FormField
                                control={form.control}
                                name="code"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>Código</FormLabel>
                                        <FormControl>
                                            <Input placeholder="DIR-001" {...field} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />

                            <FormField
                                control={form.control}
                                name="acronym"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>Sigla</FormLabel>
                                        <FormControl>
                                            <Input placeholder="DNT" {...field} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />
                        </div>

                        <FormField
                            control={form.control}
                            name="name"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Nome</FormLabel>
                                    <FormControl>
                                        <Input placeholder="Direção Nacional do Tesouro" {...field} />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        <div className="grid grid-cols-2 gap-4">
                            <FormField
                                control={form.control}
                                name="type"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>Tipo</FormLabel>
                                        <Select onValueChange={field.onChange} defaultValue={field.value} value={field.value}>
                                            <FormControl>
                                                <SelectTrigger>
                                                    <SelectValue placeholder="Selecione o tipo" />
                                                </SelectTrigger>
                                            </FormControl>
                                            <SelectContent>
                                                <SelectItem value="MINISTRY">Ministério</SelectItem>
                                                <SelectItem value="SECRETARIAT">Secretaria</SelectItem>
                                                <SelectItem value="DIRECTORATE">Direção</SelectItem>
                                                <SelectItem value="DEPARTMENT">Departamento</SelectItem>
                                                <SelectItem value="SECTION">Secção</SelectItem>
                                                <SelectItem value="OTHER">Outro</SelectItem>
                                            </SelectContent>
                                        </Select>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />

                            <FormField
                                control={form.control}
                                name="ministryId"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>Ministério</FormLabel>
                                        <Select onValueChange={field.onChange} defaultValue={field.value} value={field.value}>
                                            <FormControl>
                                                <SelectTrigger>
                                                    <SelectValue placeholder="Selecione o ministério" />
                                                </SelectTrigger>
                                            </FormControl>
                                            <SelectContent>
                                                {ministries.map((ministry) => (
                                                    <SelectItem key={ministry.id} value={ministry.id}>
                                                        {ministry.acronym} - {ministry.name}
                                                    </SelectItem>
                                                ))}
                                            </SelectContent>
                                        </Select>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />
                        </div>

                        <FormField
                            control={form.control}
                            name="parentUnitId"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Unidade Pai (Opcional)</FormLabel>
                                    <Select onValueChange={field.onChange} defaultValue={field.value} value={field.value}>
                                        <FormControl>
                                            <SelectTrigger>
                                                <SelectValue placeholder="Selecione a unidade pai" />
                                            </SelectTrigger>
                                        </FormControl>
                                        <SelectContent>
                                            <SelectItem value="none">Nenhuma</SelectItem>
                                            {parentCandidates
                                                .filter(ou => ou.id !== orgUnit?.id) // Avoid self-reference
                                                .map((ou) => (
                                                    <SelectItem key={ou.id} value={ou.id}>
                                                        {ou.acronym} - {ou.name}
                                                    </SelectItem>
                                                ))}
                                        </SelectContent>
                                    </Select>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

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

                        <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="contato@orgao.gov" {...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>

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