import {Input} from "@/components/Input/Input";
import React, {useState} from "react";
import Button from "@/components/Button/Button";
import {add, update} from "@/api/bodyTypes";
import {useModalContext} from "@/components/Modal/ModalContext";
import {useBodyTypeContext} from "@/api/context/BodyType";

export default function BodyType({ initialData }: any) {
    const { setContentModal } = useModalContext();
    const { fetchData } = useBodyTypeContext();

    const [formData, setFormData] = useState({
        id: initialData?.id || null,
        name: initialData?.name || "",
    });

    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const { name, value } = e.target;
        setFormData({
            ...formData,
            [name]: value
        });
    };

    const handleSubmit = async () => {
        if (formData.id === null) {
            await add(formData);
        } else {
            await update(formData);
        }
        fetchData();
        setContentModal(null);
    };


    return (
       <>
           <Input value={formData.name} onChange={handleChange} name="name">Наименование</Input>
           <Button onClickAction={handleSubmit}>Сохранить</Button>
       </>
    );
}
