import { useForm } from '@inertiajs/react';
import { useEffect } from 'react';
import type { FormEvent } from 'react';
import LeaveTypeController from '@/actions/App/Http/Controllers/Admin/LeaveTypeController';
import InputError from '@/components/input-error';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';

export type LeaveTypeFormValues = {
    id: number;
    code: string;
    name: string;
    deducts_balance: boolean;
    is_active: boolean;
};

type Props = {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    leaveType?: LeaveTypeFormValues | null;
};

export function LeaveTypeFormModal({
    open,
    onOpenChange,
    leaveType = null,
}: Props) {
    const isEditing = leaveType !== null;

    const form = useForm({
        name: '',
        code: '',
        deducts_balance: true,
        is_active: true,
    });

    useEffect(() => {
        if (!open) {
            return;
        }

        form.setData({
            name: leaveType?.name ?? '',
            code: leaveType?.code ?? '',
            deducts_balance: leaveType?.deducts_balance ?? true,
            is_active: leaveType?.is_active ?? true,
        });
        form.clearErrors();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [open, leaveType]);

    function submit(event: FormEvent) {
        event.preventDefault();

        const options = {
            preserveScroll: true,
            onSuccess: () => onOpenChange(false),
        };

        if (isEditing && leaveType) {
            form.put(LeaveTypeController.update.url(leaveType.id), options);

            return;
        }

        form.post(LeaveTypeController.store.url(), options);
    }

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent>
                <DialogHeader>
                    <DialogTitle>
                        {isEditing
                            ? 'Modifier le type de congé'
                            : 'Nouveau type de congé'}
                    </DialogTitle>
                    <DialogDescription>
                        Définit si ce type consomme un solde de jours.
                    </DialogDescription>
                </DialogHeader>

                <form onSubmit={submit} className="space-y-4">
                    <div className="grid gap-2">
                        <Label htmlFor="name">Nom</Label>
                        <Input
                            id="name"
                            value={form.data.name}
                            onChange={(e) =>
                                form.setData('name', e.target.value)
                            }
                            autoFocus
                        />
                        <InputError message={form.errors.name} />
                    </div>

                    <div className="grid gap-2">
                        <Label htmlFor="code">Code</Label>
                        <Input
                            id="code"
                            value={form.data.code}
                            onChange={(e) =>
                                form.setData(
                                    'code',
                                    e.target.value.toUpperCase(),
                                )
                            }
                            className="font-mono"
                            placeholder="CP"
                        />
                        <InputError message={form.errors.code} />
                    </div>

                    <label className="flex items-start gap-2">
                        <Checkbox
                            checked={form.data.deducts_balance}
                            onCheckedChange={(checked) =>
                                form.setData(
                                    'deducts_balance',
                                    checked === true,
                                )
                            }
                        />
                        <span className="grid gap-0.5">
                            <span className="text-sm">
                                Décompte un solde de jours
                            </span>
                            <span className="text-xs text-muted-foreground">
                                Désactivez pour les congés sans solde
                                (maladie, sans solde…)
                            </span>
                        </span>
                    </label>

                    <label className="flex items-center gap-2">
                        <Checkbox
                            checked={form.data.is_active}
                            onCheckedChange={(checked) =>
                                form.setData('is_active', checked === true)
                            }
                        />
                        <span className="text-sm">Type actif</span>
                    </label>

                    <DialogFooter>
                        <Button
                            type="button"
                            variant="outline"
                            onClick={() => onOpenChange(false)}
                        >
                            Annuler
                        </Button>
                        <Button type="submit" disabled={form.processing}>
                            {isEditing ? 'Enregistrer' : 'Créer'}
                        </Button>
                    </DialogFooter>
                </form>
            </DialogContent>
        </Dialog>
    );
}
