import { useForm } from '@inertiajs/react';
import { AlertCircleIcon } from 'lucide-react';
import { type FormEvent, type ReactNode, useState } from 'react';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
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 classrooms from '@/routes/classrooms';
import participants from '@/routes/participants';

export default function ParticipantImportDialog({
    classroomUuid,
    trigger,
}: {
    classroomUuid: string;
    trigger: ReactNode;
}) {
    const [open, setOpen] = useState(false);
    const form = useForm<{ file: File | null }>({ file: null });

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

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

        form.post(
            classrooms.participants.import({ classroom: classroomUuid }).url,
            {
                forceFormData: true,
                preserveScroll: true,
                onSuccess: () => handleOpenChange(false),
            },
        );
    }

    const fileErrorLines = form.errors.file
        ? form.errors.file.split('\n').filter(Boolean)
        : [];

    return (
        <Dialog open={open} onOpenChange={handleOpenChange}>
            <DialogTrigger asChild>{trigger}</DialogTrigger>
            <DialogContent>
                <DialogHeader>
                    <DialogTitle>Importa partecipanti</DialogTitle>
                    <DialogDescription>
                        Carica un file CSV o XLSX con l&apos;elenco dei
                        partecipanti da aggiungere all&apos;aula.
                    </DialogDescription>
                </DialogHeader>

                <form onSubmit={submit} className="space-y-4">
                    <div className="grid gap-2">
                        <Label htmlFor="import-file">File CSV/XLSX</Label>
                        <Input
                            id="import-file"
                            type="file"
                            accept=".csv,.xlsx"
                            onChange={(e) =>
                                form.setData(
                                    'file',
                                    e.target.files?.[0] ?? null,
                                )
                            }
                        />
                        <a
                            href={participants.template().url}
                            className="text-muted-foreground hover:text-foreground w-fit text-sm underline underline-offset-4"
                        >
                            Scarica template
                        </a>
                    </div>

                    {fileErrorLines.length > 0 && (
                        <Alert variant="destructive">
                            <AlertCircleIcon />
                            <AlertTitle>
                                Il file contiene degli errori
                            </AlertTitle>
                            <AlertDescription>
                                {fileErrorLines.map((line, i) => (
                                    <p key={i}>{line}</p>
                                ))}
                            </AlertDescription>
                        </Alert>
                    )}

                    <DialogFooter>
                        <Button
                            type="submit"
                            disabled={form.processing || !form.data.file}
                        >
                            Importa
                        </Button>
                    </DialogFooter>
                </form>
            </DialogContent>
        </Dialog>
    );
}
