import { useEffect, useMemo, useState } from "react";
import { MRT_ColumnDef } from "mantine-react-table";
import { ProductSchema } from "../../../../../client";
import { Radio } from "@mantine/core";
import { usePrefillCardsWithExcelContext } from "../../../contexts/PrefillDealsWithExcelContext.tsx";
import { ProductExcelData } from "../types.tsx";

type Props = {
    barcode: string;
}

export const useProductsTableColumns = ({ barcode }: Props) => {
    const { onProductSelectChange, barcodeProductsMap } = usePrefillCardsWithExcelContext();
    const [productData, setProductData] = useState<ProductExcelData>();

    useEffect(() => {
        setProductData(barcodeProductsMap.get(barcode));
    }, [barcodeProductsMap]);

    return useMemo<MRT_ColumnDef<ProductSchema>[]>(
        () => [
            {
                header: "Выбор",
                size: 10,
                Cell: ({ row }) => {
                    return (
                        <Radio
                            checked={productData?.selectedProduct?.id === row.original.id}
                            onChange={() => onProductSelectChange(barcode, row.original)}
                        />
                    );
                },
            },
            {
                accessorKey: "article",
                header: "Артикул",
                size: 20,
            },
            {
                accessorKey: "name",
                header: "Название",
            },
            {
                accessorKey: "brand",
                header: "Бренд",
                size: 30,
            },
            {
                accessorKey: "color",
                header: "Цвет",
                size: 30,
            },
            {
                accessorKey: "size",
                header: "Размер",
                size: 10,
            },
        ],
        [productData],
    ).filter(columnDef => (
        !(columnDef.header === "Выбор" && (productData?.products.length ?? 0) === 1)
    ));
};
