import React, { 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 OutlineButton from "@/components/ui/Buttons/OutlineButton"; import SolidButton from "@/components/ui/Buttons/SolidButton"; interface Props { dish: DishType; reloadDish: () => void; } const AddUserToDishForm = ({ dish, reloadDish }: Props) => { const [showAdd, setShowAdd] = useState(false); const [selectedUser, setSelectedUser] = useState("-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 ; } const remainingUsers = users.filter( (user: UserType) => !dish.users.find((dishUser: UserType) => dishUser.id === user.id) ); return ( <> setShowAdd(!showAdd)} disabled={remainingUsers.length === 0} type="button" > Add User { showAdd && (
Add User
)} ); }; export default AddUserToDishForm;