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 SaleModal from "@/modals/Sale";
import {Rows} from "@/components/Table/Rows";
import {Row} from "@/components/Table/Row";
import {remove} from "@/api/sales";
import {useSaleContext} from "@/api/context/Sale";
import {useCarContext} from "@/api/context/Car";
import {useCustomerContext} from "@/api/context/Customer";
import { format } from "date-fns";

export default function Sale() {
    const { setContentModal } = useModalContext();
    const { sale, fetchData } = useSaleContext();
    const { car } = useCarContext();
    const { customers } = useCustomerContext();

    if (!sale || !car || !customers) {
        return <div>Loading...</div>;
    }

    return (
        <Content>
            <Button onClickAction={() => setContentModal(<SaleModal />)}>Добавить элемент</Button>
            <Table header={['Код', 'Дата', 'Стоимость', 'Покупатель', 'Автомобиль', "Действия"]}>
                { sale.map((item, index) => {

                    const saleCar = car.find(car => car.id === item.cars_id);
                    const customer = customers.find(customer => customer.id === item.customers_id);

                    return (
                        <Rows key={index}>
                            <Row>{item.id}</Row>
                            <Row>{format(item.date, "dd.MM.yyyy")}</Row>
                            <Row>{item.price}</Row>
                            <Row>{customer ? customer.name : 'Неизвестно'}</Row>
                            <Row>{saleCar ? `Код автомобиля ${saleCar.id}` : 'Неизвестно'}</Row>
                            <Row>
                                <Button onClickAction={() => setContentModal(<SaleModal initialData={item} />)}>Редактировать</Button>
                                <Button onClickAction={async () => {
                                    await remove(item)
                                    fetchData()
                                }}>Удалить</Button>
                            </Row>
                        </Rows>
                    );

                }) }
            </Table>
        </Content>
    );
}
