import {Input} from "@/components/Input/Input";
import {useState} from "react";
import Button from "@/components/Button/Button";
import {useEngineContext} from "@/api/context/Engine";
import {add, update} from "@/api/engines";
import {useModalContext} from "@/components/Modal/ModalContext";

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

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

    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>
            <Input value={formData.powerHR} onChange={handleChange} name="powerHR">Мощность</Input>
            <Input value={formData.volume} onChange={handleChange} name="volume">Объем двигателя</Input>
            <Button onClickAction={handleSubmit}>Сохранить</Button>
        </>
    );
}
