import React, {FC, useState} from "react";
import {useRouter} from "next/navigation";
import Alert from "@/components/ui/Alert";
import {updateDish} from "@/utils/api/dishApi";
import {DishType} from "@/types/DishType";
import useRoutes from "@/hooks/useRoutes";
import Spinner from "@/components/Spinner";
import Button from "@/components/ui/Button"

interface Props {
    dish: DishType
}

const EditDishForm: FC<Props> = ({ dish }) => {
    const [name, setName] = useState<string>(dish.name);
    const [error, setError] = useState<string>("");
    const router = useRouter()
    const [loading, setLoading] = useState(false);
    const routes = useRoutes();

    const validateForm = () => {
        if (!name.trim()) {
            setError("Dish name cannot be empty.");
            return false;
        }

        return true;
    };

    const submitForm = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault()

        if (!validateForm()) return;

        setError("");
        setLoading(true);

        try {
            const result = await updateDish(dish.id, name);
            if (result) {
                router.push(routes.dish.index())
            }
        } catch (error: unknown) {
            setError(error instanceof Error ? error.message : "An unexpected error occurred");
        } finally {
            setLoading(false); // Reset loading state
        }
    }

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

    return (
        <form className="space-y-4" onSubmit={submitForm}>
            {
                error != '' && <Alert type="error" >{ error }</Alert>
            }

            {/* Dish name input */}
            <div>
                <label htmlFor="name" className="block text-sm font-medium">Dish Name</label>
                <input
                    type="text"
                    id="name"
                    name="name"
                    value={name}
                    onChange={(e) => setName(e.target.value)} // Update the name state on change
                    className="p-2 border rounded w-full bg-gray-500 border-secondary background-secondary"
                />
            </div>

            {/* Save button */}
            <Button
                type="submit"
                disabled={loading}
                className={loading ? "bg-gray-400" : ''}
                variant="primary"
                appearance="solid"
            >
                {loading ? "Saving..." : "Save"}
            </Button>
        </form>
    );
}

export default EditDishForm;