import {Input} from "@/components/Input/Input";
import React, {useState} from "react";
import Button from "@/components/Button/Button";
import {useModalContext} from "@/components/Modal/ModalContext";
import {useCarBrandContext} from "@/api/context/CarBrand";
import {add, update} from "@/api/carBrands";

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

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

    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>
            <Input value={formData.country} onChange={handleChange} name="country">Страна</Input>
            <Button onClickAction={handleSubmit}>Сохранить</Button>
        </>
    );
}
