import {
    AlertDialog,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogHeader,
    AlertDialogTitle,
} from "@/Components/ui/alert-dialog";
import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input";
import { Label } from "@/Components/ui/label";
import { useForm, usePage } from "@inertiajs/react";
import { FormEventHandler, useId, useState } from "react";
import { useAsistenciaStore } from "@/Store/useAsistenciaStore";
import { toast } from "sonner";
import { Page } from "@inertiajs/core";
import { validateInputText } from "@/Utils/validations";

import { format } from "date-fns";
import { es } from "date-fns/locale";
import { CalendarIcon } from "lucide-react";
import { Calendar } from "@/Components/ui/calendar";
import { cn } from "@/lib/utils";
import { PageProps } from "@/types/param";
import { Estudiante } from "@/types/estudiante";
import {
    Select,
    SelectContent,
    SelectGroup,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/Components/ui/select";

export function ModalCreateOrEditAsistencia() {
    const idTipo = useId();
    const idHora = useId();
    const idFecha = useId();
    const { estudiante } = usePage<PageProps<Estudiante>>().props;

    const {
        asistencia,
        openModalCreateOrEditAsistencia,
        setOpenModalCreateOrEditAsistencia,
    } = useAsistenciaStore();

    const { data, setData, post, put, reset, clearErrors, processing, errors } =
        useForm<{
            id: number | null;
            fecha: string;
            tipo: string;
            hora: string;
            id_estudiante: number | undefined;
        }>({
            id: asistencia?.id ?? null,
            fecha: asistencia?.fecha || "",
            tipo: asistencia?.tipo || "",
            hora: asistencia?.hora.slice(0, 5) || "",
            id_estudiante:
                asistencia?.id_estudiante || estudiante.id || undefined,
        });

    const submit: FormEventHandler = (e) => {
        e.preventDefault();

        const options = {
            preserveScroll: true,
            onSuccess: (response: Page<{ status?: { success?: string } }>) => {
                reset();
                const successMessage =
                    response.props.status?.success ||
                    "Operación realizada con éxito.";
                toast.success(successMessage);
                setOpenModalCreateOrEditAsistencia(false);
            },
            onError: (errors: Record<string, string> | undefined) => {
                if (errors) {
                    Object.entries(errors).forEach(([field, message]) => {
                        toast.error(`${field}: ${message}`);
                    });
                } else {
                    toast.error("Error en el formulario.");
                }
            },
        };

        if (data.id) {
            put(route("asistencias.update", { id: data.id }), options);
        } else {
            post(route("asistencias.store"), options);
        }
        clearErrors();
    };

    const handleNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const value = e.target.value;
        if (validateInputText(value)) {
            setData("tipo", value);
        }
    };

    const [selectedDate, setSelectedDate] = useState<Date | undefined>(
        data.fecha ? new Date(data.fecha) : undefined
    );

    return (
        <AlertDialog
            open={openModalCreateOrEditAsistencia}
            onOpenChange={() => setOpenModalCreateOrEditAsistencia(false)}
        >
            <AlertDialogContent>
                <AlertDialogHeader>
                    <AlertDialogTitle>
                        {asistencia?.id ? "Editar" : "Crear"} Asistencia
                    </AlertDialogTitle>
                    <AlertDialogDescription>
                        {asistencia?.id
                            ? "Modifica los datos de la asistencia y guarda los cambios."
                            : "Ingresa los datos para registrar una nueva asistencia."}
                    </AlertDialogDescription>
                </AlertDialogHeader>
                <form onSubmit={submit}>
                    <Label htmlFor={idTipo}>Tipo de Asistencia</Label>
                    <Select
                        value={data.tipo}
                        onValueChange={(value) => setData("tipo", value)}
                    >
                        <SelectTrigger className="w-full">
                            <SelectValue placeholder="Seleccione un tipo" />
                        </SelectTrigger>
                        <SelectContent>
                            <SelectGroup>
                                <SelectItem value="presente">
                                    Presente
                                </SelectItem>
                                <SelectItem value="tardanza">
                                    Tardanza
                                </SelectItem>
                                <SelectItem value="falta">Falta</SelectItem>
                            </SelectGroup>
                        </SelectContent>
                    </Select>
                    {errors.tipo && (
                        <Label className="text-destructive" htmlFor={idTipo}>
                            {errors.tipo}
                        </Label>
                    )}

                    <Label htmlFor={idFecha}>Fecha de Asistencia</Label>
                    <div className=" mt-4">
                        <Button
                            variant="outline"
                            type="button"
                            className={cn(
                                "w-full pl-3 text-left font-normal",
                                !selectedDate && "text-muted-foreground"
                            )}
                        >
                            {selectedDate ? (
                                format(selectedDate, "PPP", { locale: es })
                            ) : (
                                <span>Selecciona una fecha</span>
                            )}
                            <CalendarIcon className="ml-auto h-4 w-4 opacity-50" />
                        </Button>
                        <div className=" flex justify-center">
                            <Calendar
                                mode="single"
                                selected={selectedDate}
                                onSelect={(date) => {
                                    setSelectedDate(date);
                                    if (date) {
                                        setData(
                                            "fecha",
                                            date.toISOString().split("T")[0]
                                        );
                                    }
                                }}
                                disabled={(date) =>
                                    date > new Date() ||
                                    date < new Date("1900-01-01")
                                }
                                initialFocus
                            />
                        </div>
                    </div>

                    <Label htmlFor={idHora}>Hora</Label>
                    <Input
                        id={idHora}
                        type="time"
                        step="60"
                        value={data.hora}
                        className="mt-1 block w-full"
                        placeholder="Seleccione la hora"
                        onChange={(e) => setData("hora", e.target.value)}
                        required
                    />

                    {errors.hora && (
                        <Label className="text-destructive" htmlFor={idHora}>
                            {errors.hora}
                        </Label>
                    )}

                    <footer className="flex justify-around gap-4 mt-4">
                        <Button
                            type="button"
                            onClick={() =>
                                setOpenModalCreateOrEditAsistencia(false)
                            }
                            variant="secondary"
                        >
                            Cancelar
                        </Button>
                        <Button type="submit" disabled={processing}>
                            Guardar
                        </Button>
                    </footer>
                </form>
            </AlertDialogContent>
        </AlertDialog>
    );
}
