import { useEffect } 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 { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { MinistryDTO } from '@/types/org';

const ministrySchema = 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'),
    description: z.string().max(255, 'Descrição deve ter no máximo 255 caracteres').optional(),
    logo: z.string().optional(),
});

type MinistryFormData = z.infer<typeof ministrySchema>;

interface MinistryFormModalProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    ministry?: MinistryDTO | null;
    onSubmit: (data: MinistryFormData) => Promise<void>;
}

export function MinistryFormModal({ open, onOpenChange, ministry, onSubmit }: MinistryFormModalProps) {
    const form = useForm<MinistryFormData>({
        resolver: zodResolver(ministrySchema),
        defaultValues: {
            code: '',
            name: '',
            acronym: '',
            description: '',
            logo: '',
        },
    });

    useEffect(() => {
        if (ministry) {
            form.reset({
                code: ministry.code,
                name: ministry.name,
                acronym: ministry.acronym,
                description: ministry.description || '',
                logo: ministry.logo || '',
            });
        } else {
            form.reset({
                code: '',
                name: '',
                acronym: '',
                description: '',
                logo: '',
            });
        }
    }, [ministry, open, form]);

    const handleSubmit = async (data: MinistryFormData) => {
        await onSubmit(data);
    };

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="sm:max-w-[500px]">
                <DialogHeader>
                    <DialogTitle>{ministry ? 'Editar Ministério' : 'Novo Ministério'}</DialogTitle>
                    <DialogDescription>
                        {ministry
                            ? 'Atualize as informações do ministério'
                            : 'Preencha os dados para criar um novo ministério'}
                    </DialogDescription>
                </DialogHeader>

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

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

                        <FormField
                            control={form.control}
                            name="name"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Nome</FormLabel>
                                    <FormControl>
                                        <Input placeholder="Ministério das Finanças" {...field} />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        <FormField
                            control={form.control}
                            name="description"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Descrição</FormLabel>
                                    <FormControl>
                                        <Textarea placeholder="Descrição opcional..." {...field} />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        <FormItem>
                            <FormLabel>Logótipo</FormLabel>
                            <FormControl>
                                <div className="flex items-center gap-4">
                                    {form.watch('logo') && (
                                        <img
                                            src={form.watch('logo')}
                                            alt="Logo preview"
                                            className="h-16 w-16 object-contain border rounded"
                                        />
                                    )}
                                    <Input
                                        type="file"
                                        accept="image/*"
                                        onChange={(e) => {
                                            const file = e.target.files?.[0];
                                            if (file) {
                                                const reader = new FileReader();
                                                reader.onloadend = () => {
                                                    form.setValue('logo', reader.result as string);
                                                };
                                                reader.readAsDataURL(file);
                                            }
                                        }}
                                    />
                                </div>
                            </FormControl>
                            <FormMessage />
                        </FormItem>

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