import React, { FC, useState } from "react";
import { DishType } from "@/types/DishType";
import { UserType } from "@/types/UserType";
import { useFetchUsers } from "@/hooks/useFetchUsers";
import Spinner from "@/components/Spinner";
import {addUserToDish} from "@/utils/api/dishApi";
import Button from "@/components/ui/Button";

interface Props {
    dish: DishType;
    reloadDish: () => void;
}

const AddUserToDishForm: FC<Props> = ({ dish, reloadDish }) => {
    const [showAdd, setShowAdd] = useState<boolean>(false);
    const [selectedUser, setSelectedUser] = useState<string>("-1");
    const { users, isLoading: isUsersLoading } = useFetchUsers();

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();

        if (selectedUser === "-1") {
            alert("Please select a valid user.");
            return;
        }

        const userToAdd = users.find((user: UserType) => user.id === parseInt(selectedUser));

        if (!userToAdd) {
            alert("User not found.");
            return;
        }

        addUserToDish(dish.id, userToAdd.id)
            .then(() => {
                setShowAdd(false);
                setSelectedUser("-1");
                reloadDish();
            })
            .catch(() => {
                alert("Failed to add user, please try again.");
            });
    };

    if (isUsersLoading) {
        return <Spinner />;
    }

    const remainingUsers = users.filter(
        (user: UserType) =>
            !dish.users.find((dishUser: UserType) => dishUser.id === user.id)
    );

    return (
        <>
            <Button
                appearance="outline"
                className="mb-2 flex-none w-fit ml-auto"
                onClick={() => setShowAdd(!showAdd)}
                disabled={remainingUsers.length === 0}
                type="button"
            >
                Add User
            </Button>

            { showAdd && (
                <div className="mt-2 mb-5 w-full">
                <form onSubmit={handleSubmit}>
                    <div className="flex">
                        <div className="flex-grow pt-2">
                            <select
                                value={selectedUser}
                                onChange={(e) => setSelectedUser(e.target.value)}
                                className="p-2 border rounded w-full bg-secondary border-secondary"
                            >
                                <option value="-1">Select user</option>
                                {remainingUsers.map((user: UserType) => (
                                    <option key={user.id} value={user.id}>
                                        {user.name}
                                    </option>
                                ))}
                            </select>
                        </div>

                        <div className="flex-none py-2 pr-2 pl-4">
                            <Button type="submit"
                                         appearance="solid"
                                         variant="primary"
                                         size="small"
                                         className="mt-1"
                            >
                                Add User
                            </Button>
                        </div>
                    </div>
                </form>
                </div>
            )}
        </>
    );
};

export default AddUserToDishForm;