import Button from "@/components/Button/Button";
import {useModalContext} from "@/components/Modal/ModalContext";
import {OptionType, Select} from "@/components/Select/Select";
import React, {useState} from "react";
import {add, update} from "@/api/sales";
import {useSaleContext} from "@/api/context/Sale";
import {Input} from "@/components/Input/Input";
import {useCarContext} from "@/api/context/Car";
import {useCustomerContext} from "@/api/context/Customer";
import {InputDate} from "@/components/Input/InputDate";
import {SingleValue} from "react-select";

export default function Sale({ initialData }:any) {
    const { setContentModal } = useModalContext();
    const { fetchData } = useSaleContext();
    const { car } = useCarContext();
    const { customers } = useCustomerContext();

    const carOptions = car?.map((car: any) => ({
        value: car.id,
        label: `Код автомобиля ${car.id}`
    })) || [];

    const customersOptions = customers?.map((customer: any) => ({
        value: customer.id,
        label: customer.name
    })) || [];


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

    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 (
        <>
            <InputDate value={formData.date} onChange={handleChange} name="date">Дата продажи</InputDate>
            <Input value={formData.price} onChange={handleChange} name="price">Цена</Input>
            <Select options={carOptions}
                    placeholder={"Автомобиль"}
                    value={formData.cars_id}
                    onChange={(e: SingleValue<OptionType>) => {
                        setFormData({
                            ...formData,
                            cars_id: e ? e.value : null
                        });
                    }} name="cars_id"/>
            <Select options={customersOptions}
                    placeholder={"Покупатель"}
                    value={formData.customers_id}
                    onChange={(e: SingleValue<OptionType>) => {
                        setFormData({
                            ...formData,
                            customers_id: e ? e.value : null
                        });
                    }} name="customers_id"/>
            <Button onClickAction={handleSubmit}>Сохранить</Button>
        </>
    );
}
