import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { Head, useForm } from "@inertiajs/react";
import { ICancellation, IKid, IPaginator, IUser, PageProps } from "@/types";
import PrimaryButton from "@/Components/PrimaryButton";
import InputLabel from "@/Components/InputLabel";
import TextInput from "@/Components/TextInput";
import React, { useState } from "react";
import Modal from "@/Components/Modal";
import SelectInput from "@/Components/SelectInput";
import PaginatorComponent from "@/Components/Paginator";

interface FormData {
    start_date: string;
    end_date: string;
    kid_id: string;
}

export default function Meal({
    auth,
    user,
    kids,
    cancellations,
}: PageProps<{
    user: IUser;
    cancellations: IPaginator<ICancellation>;
    kids: IKid[];
}>) {
    const { data, setData, post, errors, reset } = useForm<FormData>({
        start_date: "",
        end_date: "",
        kid_id: "",
    });

    const [selectedCancellation, setSelectedCancellation] =
        useState<ICancellation | null>(null);
    const { delete: destroy } = useForm();
    const [showDeleteModal, setShowDeleteModal] = useState(false);

    const handleCancelMeal = (e: React.FormEvent) => {
        e.preventDefault();
        post(
            route("admin.users.cancellations.store", {
                user: user.id,
            }),
            {
                onSuccess: () => reset("start_date", "end_date", "kid_id"),
            }
        );
    };

    const handleDelete = () => {
        if (selectedCancellation) {
            destroy(
                route("admin.users.cancellations.destroy", {
                    user: selectedCancellation.user_id,
                    cancellation: selectedCancellation.id,
                }),
                {
                    onFinish: () => {
                        setShowDeleteModal(false);
                        setSelectedCancellation(null);
                    },
                }
            );
        }
    };

    const kidOptions = kids.map((kid) => ({
        label: kid.full_name,
        value: kid.id,
    }));

    return (
        <AuthenticatedLayout
            user={auth.user}
            header={"Étkezés lemondás -" + user.full_name}
        >
            <Head title="Étkezés lemondás" />
            <div className="items-center mb-8 m-2">
                {Object.keys(errors).length > 0 && (
                    <div className="mt-4 text-red-600">
                        <ul>
                            {Object.entries(errors).map(([field, messages]) => (
                                <li key={field}>
                                    {Array.isArray(messages) ? (
                                        messages.map((message, index) => (
                                            <p key={index}>{message}</p>
                                        ))
                                    ) : (
                                        <p>{messages}</p>
                                    )}
                                </li>
                            ))}
                        </ul>
                    </div>
                )}
                <form onSubmit={handleCancelMeal}>
                    <div className="flex flex-col md:flex-row md:space-x-4 mb-4">
                        <div className="flex-1 mb-4 md:mb-0">
                            <InputLabel htmlFor="start_date" value="Ettől:" />
                            <TextInput
                                id="start_date"
                                type="date"
                                value={data.start_date}
                                onChange={(e) =>
                                    setData("start_date", e.target.value)
                                }
                                className={`mt-1 block w-full ${
                                    errors.start_date ? "border-red-500" : ""
                                }`}
                            />
                        </div>
                        <div className="flex-1 mb-4 md:mb-0">
                            <InputLabel htmlFor="end_date" value="Eddig:" />
                            <TextInput
                                id="end_date"
                                type="date"
                                value={data.end_date}
                                onChange={(e) =>
                                    setData("end_date", e.target.value)
                                }
                                className={`mt-1 block w-full ${
                                    errors.end_date ? "border-red-500" : ""
                                }`}
                            />
                        </div>
                        <div className="flex-1 mb-4 md:mb-0">
                            <InputLabel htmlFor="kid" value="Gyermek:" />
                            <SelectInput
                                id="kid"
                                value={data.kid_id}
                                onChange={(e) =>
                                    setData("kid_id", e.target.value)
                                }
                                options={kidOptions}
                                className={`mt-1 block w-full ${
                                    errors.kid_id ? "border-red-500" : ""
                                }`}
                            />
                        </div>
                    </div>
                    <div className="flex justify-end">
                        <PrimaryButton type="submit">Lemondás</PrimaryButton>
                    </div>
                </form>
            </div>

            <div className="text-black p-6 rounded-lg md:mt-12">
                <h2 className="text-2xl font-semibold mb-4">
                    Lemondott Étkezések:
                </h2>
                <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
                    {cancellations.data.map((cancellation) => (
                        <div
                            key={cancellation.id}
                            className="bg-babolygo-ocean p-4 rounded-lg shadow-md flex flex-col items-start"
                        >
                            <span className="font-semibold text-lg">
                                {cancellation.kid.full_name}
                            </span>
                            <span>{cancellation.date}</span>
                            <PrimaryButton
                                className="mt-4 bg-red-500 text-white py-1 px-2 rounded hover:bg-red-600"
                                onClick={() => {
                                    setSelectedCancellation(cancellation);
                                    setShowDeleteModal(true);
                                }}
                            >
                                Törlés
                            </PrimaryButton>
                        </div>
                    ))}
                </div>
                <div className="m-5 flex justify-center">
                    <PaginatorComponent {...cancellations} />
                </div>
            </div>
            <Modal
                show={showDeleteModal}
                onClose={() => setShowDeleteModal(false)}
            >
                <div className="p-6">
                    <h2 className="text-lg font-semibold mb-4">
                        Biztosan törölni szeretnéd?
                    </h2>
                    <p className="mb-4">Ez a művelet nem vonható vissza.</p>
                    <div className="flex justify-end">
                        <PrimaryButton
                            onClick={() => setShowDeleteModal(false)}
                            className=" mr-4"
                        >
                            Mégse
                        </PrimaryButton>
                        <PrimaryButton
                            onClick={handleDelete}
                            className="bg-red-600 text-white px-4 py-2 hover:bg-red-700"
                        >
                            Törlés
                        </PrimaryButton>
                    </div>
                </div>
            </Modal>
        </AuthenticatedLayout>
    );
}
