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 {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Textarea } from '@/components/ui/textarea';
import { PositionDTO } from '@/types/org';
import { useOrgUnits } from '@/hooks/useOrgUnits';

const positionSchema = z.object({
    code: z.string().min(1, 'Código é obrigatório').max(20, 'Código deve ter no máximo 20 caracteres'),
    title: z.string().min(1, 'Título é obrigatório').max(100, 'Título deve ter no máximo 100 caracteres'),
    description: z.string().max(255, 'Descrição deve ter no máximo 255 caracteres').optional(),
    level: z.string().min(1, 'Nível é obrigatório').max(20, 'Nível deve ter no máximo 20 caracteres'),
    orgUnitId: z.string().min(1, 'Unidade Orgânica é obrigatória'),
    isManagerial: z.boolean().default(false),
});

type PositionFormData = z.infer<typeof positionSchema>;

interface PositionFormModalProps {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    position?: PositionDTO | null;
    onSubmit: (data: PositionFormData) => Promise<void>;
}

export function PositionFormModal({ open, onOpenChange, position, onSubmit }: PositionFormModalProps) {
    const { orgUnits } = useOrgUnits({ size: 100 }); // Fetch all org units for select

    const form = useForm<PositionFormData>({
        resolver: zodResolver(positionSchema),
        defaultValues: {
            code: '',
            title: '',
            description: '',
            level: '',
            orgUnitId: '',
            isManagerial: false,
        },
    });

    useEffect(() => {
        if (position) {
            form.reset({
                code: position.code,
                title: position.title,
                description: position.description || '',
                level: position.level,
                orgUnitId: position.orgUnitId,
                isManagerial: position.isManagerial,
            });
        } else {
            form.reset({
                code: '',
                title: '',
                description: '',
                level: '',
                orgUnitId: '',
                isManagerial: false,
            });
        }
    }, [position, open, form]);

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

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="sm:max-w-[500px]">
                <DialogHeader>
                    <DialogTitle>{position ? 'Editar Cargo' : 'Novo Cargo'}</DialogTitle>
                    <DialogDescription>
                        {position
                            ? 'Atualize as informações do cargo'
                            : 'Preencha os dados para criar um novo cargo'}
                    </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="CAR-001" {...field} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />

                            <FormField
                                control={form.control}
                                name="level"
                                render={({ field }) => (
                                    <FormItem>
                                        <FormLabel>Nível</FormLabel>
                                        <FormControl>
                                            <Input placeholder="L1" {...field} />
                                        </FormControl>
                                        <FormMessage />
                                    </FormItem>
                                )}
                            />
                        </div>

                        <FormField
                            control={form.control}
                            name="title"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Título</FormLabel>
                                    <FormControl>
                                        <Input placeholder="Analista Financeiro" {...field} />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />

                        <FormField
                            control={form.control}
                            name="orgUnitId"
                            render={({ field }) => (
                                <FormItem>
                                    <FormLabel>Unidade Orgânica</FormLabel>
                                    <Select onValueChange={field.onChange} defaultValue={field.value} value={field.value}>
                                        <FormControl>
                                            <SelectTrigger>
                                                <SelectValue placeholder="Selecione a unidade" />
                                            </SelectTrigger>
                                        </FormControl>
                                        <SelectContent>
                                            {orgUnits.map((ou) => (
                                                <SelectItem key={ou.id} value={ou.id}>
                                                    {ou.acronym} - {ou.name}
                                                </SelectItem>
                                            ))}
                                        </SelectContent>
                                    </Select>
                                    <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>
                            )}
                        />

                        <FormField
                            control={form.control}
                            name="isManagerial"
                            render={({ field }) => (
                                <FormItem className="flex flex-row items-start space-x-3 space-y-0">
                                    <FormControl>
                                        <Checkbox
                                            checked={field.value}
                                            onCheckedChange={field.onChange}
                                        />
                                    </FormControl>
                                    <div className="space-y-1 leading-none">
                                        <FormLabel>Cargo de Chefia</FormLabel>
                                    </div>
                                </FormItem>
                            )}
                        />

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