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 { useConductaStore } from "@/Store/useConductaStore";
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";

export function ModalCreateOrEditConducta() {
    const idConducta = useId();
    const idObservacion = useId();
    const idFecha = useId();

    const { estudiante } = usePage<PageProps<Estudiante>>().props;

    const {
        conducta,
        openModalCreateOrEditConducta,
        setOpenModalCreateOrEditConducta,
    } = useConductaStore();

    const { data, setData, post, put, reset, clearErrors, processing, errors } =
        useForm<{
            id: number | null;
            fecha: string;
            conducta: string;
            observacion: string;
            id_estudiante: number | undefined;
        }>({
            id: conducta?.id ?? null,
            fecha: conducta?.fecha || "",
            conducta: conducta?.conducta || "",
            observacion: conducta?.observacion || "",
            id_estudiante:
                conducta?.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);
                setOpenModalCreateOrEditConducta(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("conductas.update", { id: data.id }), options);
        } else {
            post(route("conductas.store"), options);
        }
        clearErrors();
    };

    const handleConductaChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const value = e.target.value;
        if (validateInputText(value)) {
            setData("conducta", value);
        }
    };
    const handleObservacionChange = (
        e: React.ChangeEvent<HTMLInputElement>
    ) => {
        const value = e.target.value;
        if (validateInputText(value)) {
            setData("observacion", value);
        }
    };

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

    return (
        <AlertDialog
            open={openModalCreateOrEditConducta}
            onOpenChange={() => setOpenModalCreateOrEditConducta(false)}
        >
            <AlertDialogContent>
                <AlertDialogHeader>
                    <AlertDialogTitle>
                        {conducta?.id ? "Editar" : "Crear"} Conducta
                    </AlertDialogTitle>
                    <AlertDialogDescription>
                        {conducta?.id
                            ? "Modifica los datos de la conducta y guarda los cambios."
                            : "Ingresa los datos para registrar una nueva conducta."}
                    </AlertDialogDescription>
                </AlertDialogHeader>
                <form onSubmit={submit}>
                    <Label htmlFor={idConducta}>Conducta</Label>
                    <Input
                        id={idConducta}
                        type="text"
                        value={data.conducta}
                        className="mt-1 block w-full"
                        placeholder="Nombre de la conducta"
                        onChange={handleConductaChange}
                        required
                    />
                    {errors.conducta && (
                        <Label
                            className="text-destructive"
                            htmlFor={idConducta}
                        >
                            {errors.conducta}
                        </Label>
                    )}
                    <Label htmlFor={idObservacion}>Observación</Label>
                    <Input
                        id={idObservacion}
                        type="text"
                        value={data.observacion}
                        className="mt-1 block w-full"
                        placeholder="Nombre de la conducta"
                        onChange={handleObservacionChange}
                        required
                    />
                    {errors.observacion && (
                        <Label
                            className="text-destructive"
                            htmlFor={idObservacion}
                        >
                            {errors.observacion}
                        </Label>
                    )}
                    <Label>Fecha</Label>
                    <Label htmlFor={idFecha}>Fecha</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>

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