import {Input} from "@/components/Input/Input";
import {useState} from "react";
import Button from "@/components/Button/Button";
import {add, update} from "@/api/transmissions";
import {useModalContext} from "@/components/Modal/ModalContext";
import {useTransmissionContext} from "@/api/context/Transmission";

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

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

    const handleChange = (e: any) => {
        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.type} onChange={handleChange} name="type">Название</Input>
            <Button onClickAction={handleSubmit}>Сохранить</Button>
        </>
    );
}
