import {Input} from "@/components/Input/Input";
import React, {useState} from "react";
import Button from "@/components/Button/Button";
import {OptionType, Select} from "@/components/Select/Select";
import {useCarModelContext} from "@/api/context/CarModel";
import {add, update} from "@/api/trims";
import {useModalContext} from "@/components/Modal/ModalContext";
import {useTrimContext} from "@/api/context/Trim";
import {SingleValue} from "react-select";

export default function Trim({ initialData }: any) {
    const { carModel } = useCarModelContext();
    const { setContentModal } = useModalContext();
    const { fetchData } = useTrimContext();

    const carModelOptions = carModel?.map((model: any) => ({
        value: model.id,
        label: model.name
    })) || [];

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

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

    const handleChangeSelect = (e: SingleValue<OptionType>) => {
        setFormData({
            ...formData,
            car_models_id: e ? e.value : null
        });
    };

    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.price} onChange={handleChange} name="price">Цена</Input>
            <Select options={carModelOptions} placeholder={"Модель автомобиля"} value={formData.car_models_id}
                    onChange={handleChangeSelect} name="car_brands_id"/>
            <Button onClickAction={handleSubmit}>Сохранить</Button>
        </>
    );
}
