import { useForm } from '@inertiajs/react';
import { type FormEvent, type ReactNode, useState } from 'react';
import InputError from '@/components/input-error';
import { Button } from '@/components/ui/button';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
    DialogTrigger,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import classrooms from '@/routes/classrooms';
import type {
    Participant,
    ParticipantRole,
} from '@/components/classrooms/types';

type Props = {
    classroomUuid: string;
    participant?: Participant;
    trigger: ReactNode;
};

export default function ParticipantFormDialog({
    classroomUuid,
    participant,
    trigger,
}: Props) {
    const [open, setOpen] = useState(false);
    const isEdit = Boolean(participant);

    const form = useForm({
        first_name: participant?.first_name ?? '',
        last_name: participant?.last_name ?? '',
        fiscal_code: participant?.fiscal_code ?? '',
        email: participant?.email ?? '',
        phone: participant?.phone ?? '',
        role: (participant?.role ?? 'learner') as ParticipantRole,
    });

    function handleOpenChange(next: boolean) {
        setOpen(next);
        if (!next) {
            form.reset();
            form.clearErrors();
        }
    }

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

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

        if (participant) {
            form.patch(
                classrooms.participants.update({
                    classroom: classroomUuid,
                    participant: participant.id,
                }).url,
                options,
            );
        } else {
            form.post(
                classrooms.participants.store({ classroom: classroomUuid }).url,
                options,
            );
        }
    }

    return (
        <Dialog open={open} onOpenChange={handleOpenChange}>
            <DialogTrigger asChild>{trigger}</DialogTrigger>
            <DialogContent>
                <DialogHeader>
                    <DialogTitle>
                        {isEdit
                            ? 'Modifica partecipante'
                            : 'Aggiungi partecipante'}
                    </DialogTitle>
                    <DialogDescription>
                        {isEdit
                            ? 'Aggiorna i dati anagrafici del partecipante.'
                            : "Inserisci i dati del discente o docente da aggiungere all'aula."}
                    </DialogDescription>
                </DialogHeader>

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

                    <div className="grid gap-2">
                        <Label htmlFor="fiscal_code">Codice fiscale</Label>
                        <Input
                            id="fiscal_code"
                            value={form.data.fiscal_code}
                            maxLength={16}
                            className="uppercase"
                            onChange={(e) =>
                                form.setData(
                                    'fiscal_code',
                                    e.target.value.toUpperCase(),
                                )
                            }
                        />
                        <InputError message={form.errors.fiscal_code} />
                    </div>

                    <div className="grid grid-cols-2 gap-4">
                        <div className="grid gap-2">
                            <Label htmlFor="email">Email</Label>
                            <Input
                                id="email"
                                type="email"
                                value={form.data.email}
                                onChange={(e) =>
                                    form.setData('email', e.target.value)
                                }
                            />
                            <InputError message={form.errors.email} />
                        </div>
                        <div className="grid gap-2">
                            <Label htmlFor="phone">Telefono</Label>
                            <Input
                                id="phone"
                                value={form.data.phone}
                                onChange={(e) =>
                                    form.setData('phone', e.target.value)
                                }
                            />
                            <InputError message={form.errors.phone} />
                        </div>
                    </div>

                    <div className="grid gap-2">
                        <Label htmlFor="role">Ruolo</Label>
                        <Select
                            value={form.data.role}
                            onValueChange={(value) =>
                                form.setData('role', value as ParticipantRole)
                            }
                        >
                            <SelectTrigger id="role" className="w-full">
                                <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value="learner">Allievo</SelectItem>
                                <SelectItem value="trainer">Docente</SelectItem>
                            </SelectContent>
                        </Select>
                        <InputError message={form.errors.role} />
                    </div>

                    <DialogFooter>
                        <Button type="submit" disabled={form.processing}>
                            {isEdit ? 'Salva modifiche' : 'Aggiungi'}
                        </Button>
                    </DialogFooter>
                </form>
            </DialogContent>
        </Dialog>
    );
}
