import Content from "@/components/Content/Content";
import {Table} from "@/components/Table/Table";
import Button from "@/components/Button/Button";
import {useModalContext} from "@/components/Modal/ModalContext";
import CarModelsModal from "@/modals/CarModel";
import {useCarModelContext} from "@/api/context/CarModel";
import {Rows} from "@/components/Table/Rows";
import {Row} from "@/components/Table/Row";
import {remove} from "@/api/carModels";
import {useCarBrandContext} from "@/api/context/CarBrand";

export default function CarModel() {
    const { setContentModal } = useModalContext();
    const { carModel, fetchData } = useCarModelContext();
    const { carBrands } = useCarBrandContext();

    if (!carModel || !carBrands) {
        return <div>Loading...</div>;
    }

    return (
        <Content>
            <Button onClickAction={() => setContentModal(<CarModelsModal />)}>Добавить элемент</Button>
            <Table header={['Код', 'Наименование', 'Год начала', 'Год окончания', "Марка автомобиля", "Действия"]}>
                { carModel.map((item, index) => {
                    const brand = carBrands.find(brand => brand.id === item.car_brands_id);
                    return (
                        <Rows key={index}>
                            <Row>{item.id}</Row>
                            <Row>{item.name}</Row>
                            <Row>{item.yearStart}</Row>
                            <Row>{item.yearEnd}</Row>
                            <Row>{brand ? brand.name : 'Неизвестно'}</Row>
                            <Row>
                                <Button onClickAction={() => setContentModal(<CarModelsModal initialData={item} />)}>Редактировать</Button>
                                <Button onClickAction={async () => {
                                    await remove(item)
                                    fetchData()
                                }}>Удалить</Button>
                            </Row>
                        </Rows>
                    );
                }) }
            </Table>
        </Content>
    );
}
