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 TrimModal from "@/modals/Trim";
import {Rows} from "@/components/Table/Rows";
import {Row} from "@/components/Table/Row";
import {remove} from "@/api/trims";
import {useCarModelContext} from "@/api/context/CarModel";
import {useTrimContext} from "@/api/context/Trim";

export default function Trim() {
    const { setContentModal } = useModalContext();
    const { carModel } = useCarModelContext();
    const { trim, fetchData } = useTrimContext();

    if (!carModel || !trim) {
        return <div>Loading...</div>;
    }
    return (
        <Content>
            <Button onClickAction={() => setContentModal(<TrimModal />)}>Добавить элемент</Button>
            <Table header={['Код', 'Название комплектации', 'Цена', 'Модель автомобиля', "Действия"]}>
                { trim.map((item, index) => {
                    const model = carModel.find(model => model.id === item.car_models_id);
                    return (
                        <Rows key={index}>
                            <Row>{item.id}</Row>
                            <Row>{item.name}</Row>
                            <Row>{item.price}</Row>
                            <Row>{model ? model.name : 'Неизвестно'}</Row>
                            <Row>
                                <Button onClickAction={() => setContentModal(<TrimModal initialData={item} />)}>Редактировать</Button>
                                <Button onClickAction={async () => {
                                    await remove(item)
                                    fetchData()
                                }}>Удалить</Button>
                            </Row>
                        </Rows>
                    );
                }) }
            </Table>
        </Content>
    );
}
