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

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

    const carBrandOptions = carBrands?.map((brand: any) => ({
        value: brand.id,
        label: brand.name
    })) || [];

    const [formDataCarModel, setFormDataCarModel] = useState({
        id: initialData?.id || null,
        name: initialData?.name || "",
        yearStart: initialData?.yearStart || "",
        yearEnd: initialData?.yearEnd || "",
        car_brands_id: initialData?.car_brands_id  || null,
    });

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

    const handleChangeSelect = (e: SingleValue<OptionType>) => {
        setFormDataCarModel({
            ...formDataCarModel,
            car_brands_id: e ? e.value : null
        });
    };

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

    return (
        <>
            <Input value={formDataCarModel.name} onChange={handleChange} name="name">Наименование</Input>
            <Input value={formDataCarModel.yearStart} onChange={handleChange} name="yearStart">Год начала</Input>
            <Input value={formDataCarModel.yearEnd} onChange={handleChange} name="yearEnd">Год окончания</Input>
            <Select options={carBrandOptions} placeholder={"Марака автомобиля"} value={formDataCarModel.car_brands_id}
                    onChange={handleChangeSelect} name="car_brands_id"/>
            <Button onClickAction={handleSubmit}>Сохранить</Button>
        </>
    );
}
