import {FC, FormEvent, useMemo, useState} from "react";
import {DishType} from "@/types/DishType";
import {ScheduledUserDishType} from "@/types/ScheduledUserDishType";
import {updateScheduledUserDish} from "@/utils/api/scheduledUserDishesApi";
import Alert from "@/components/ui/Alert";
import classNames from "classnames";

interface Props {
    scheduledUserDish: ScheduledUserDishType
    allDishes: DishType[]
}

const UserDishEditCard: FC<Props> = ({ scheduledUserDish, allDishes }) => {
    const [selectedUserDishId, setSelectedUserDishId] = useState<number>(scheduledUserDish.user_dish ? scheduledUserDish.user_dish.id : 0)
    const [errorMessage, setErrorMessage] = useState<string>("")
    const [isSuccess, setIsSuccess] = useState(false);

    const selectStyle = classNames(
        'p-2', 'rounded', 'w-full', 'background-secondary',
        'focus:outline-none',
        'transition-[border-color] ease-out duration-1000', 'border-2', // Keep consistent base styles
        {
            'border-green-500': isSuccess,                      // Green border when successful
            'border-red-500': !isSuccess && errorMessage !== "", // Red border when there's an error
            'border-secondary': !isSuccess && errorMessage === "", // Default border for neutral state
        }
    )

    const handleOnChange = (e: FormEvent<HTMLSelectElement>) => {
        const userDishId = parseInt(e.currentTarget.value);
        setSelectedUserDishId(userDishId);

        updateScheduledUserDish(scheduledUserDish.id, userDishId)
            .then(() => {
                setIsSuccess(false);
                setTimeout(() => {
                    setIsSuccess(true);
                    setTimeout(() => setIsSuccess(false), 1000);
                }, 0);
            })
            .catch((error) => {
                setErrorMessage(error); // Log API errors
            });
    };

    const filteredDishes = useMemo(() =>
        allDishes.filter((dish: DishType) =>
            dish.users.some((user) => user.id === scheduledUserDish.user_dish.user.id)
        ),
        [allDishes, scheduledUserDish.user_dish.user.id]
    )

    return (
        <div className="m-5 mb-10">
            <div className="text-2xl">{scheduledUserDish.user_dish.user.name}</div>

            { errorMessage !== "" && <Alert type="error">{ errorMessage }</Alert> }

            <label htmlFor="name" className="block text-sm font-medium mt-2">Dish</label>
            <select
                value={selectedUserDishId}
                onChange={(e) => handleOnChange(e)}
                className={selectStyle}
            >
                <option key={0} value={0}>Skip Dish</option>
                {
                    filteredDishes
                        .map((dish: DishType) =>
                            <option key={dish.id} value={dish.id}>
                                {dish.name}
                            </option>
                        )
                }
            </select>
        </div>
    );
};

export default UserDishEditCard;