import {FC} from "react";
import {
    DealProductSchema,
    DealProductServiceSchema,
    GetServiceKitSchema,
    ProductSchema
} from "../../../../../../client";
import styles from './ProductView.module.css';
import {ActionIcon, Box, Flex, Image, NumberInput, rem, Text, Title, Tooltip} from '@mantine/core';
import ProductServicesTable from "../ProductServicesTable/ProductServicesTable.tsx";
import {isNil, isNumber} from "lodash";
import {IconBarcode, IconEdit, IconTrash} from "@tabler/icons-react";
import {modals} from "@mantine/modals";
import {ServiceType} from "../../../../../../shared/enums/ServiceType.ts";
import useDealProductAndServiceTabState from "../../hooks/useProductAndServiceTabState.tsx";

type Props = {
    product: DealProductSchema;
    onChange?: (item: DealProductSchema) => void;
    onDelete?: (item: DealProductSchema) => void
    onCopyServices?: (item: DealProductSchema) => void;
    onKitAdd?: (item: DealProductSchema, kit: GetServiceKitSchema) => void;
    onProductEdit: (product: ProductSchema) => void;
}
type ProductFieldNames = {
    [K in keyof ProductSchema]: string
}
export const ProductFieldNames: Partial<ProductFieldNames> = {
    color: "Цвет",
    article: "Артикул",
    size: "Размер",
    brand: "Бренд",
    composition: "Состав",
    additionalInfo: "Доп. информация",
}
const ProductView: FC<Props> = ({
                                    product,
                                    onDelete,
                                    onChange,
                                    onCopyServices,
                                    onKitAdd,
                                    onProductEdit
                                }) => {
    const {dealState} = useDealProductAndServiceTabState();
    const isLocked = Boolean(dealState.deal?.billRequest);
    const onDeleteClick = () => {
        if (!onDelete) return;
        onDelete(product);
    }

    const onServiceDelete = (item: DealProductServiceSchema) => {
        if (!onChange) return;
        onChange({
            ...product,
            services: product.services.filter(service => service.service.id !== item.service.id)
        });

    }
    const onServiceCreate = (item: DealProductServiceSchema) => {
        if (!onChange) return;
        onChange({
            ...product,
            services: [...product.services, item]
        })
    }

    const onServiceChange = (item: DealProductServiceSchema) => {
        if (!onChange) return;
        onChange({
            ...product,
            services: product.services.map(service => service.service.id === item.service.id ? item : service)
        })
    }

    const onQuantityChange = (quantity: number) => {
        if (!onChange) return;
        onChange({
            ...product,
            quantity
        })
    }
    const onPrintBarcodeClick = () => {
        modals.openContextModal({
            modal: "printBarcode",
            innerProps: {
                productId: product.product.id,
                defaultQuantity: product.quantity
            },
            title: 'Печать штрихкода',
        })
    }

    const onKitAddClick = () => {
        if (!onKitAdd) return;
        modals.openContextModal({
            modal: "servicesKitSelectModal",
            innerProps: {
                onSelect: (kit) => onKitAdd(product, kit),
                serviceType: ServiceType.PRODUCT_SERVICE
            },
            withCloseButton: false
        })
    }


    const onProductEditClick = () => {
        modals.openContextModal({
            modal: "createProduct",
            title: 'Редактирование товара',
            withCloseButton: false,
            innerProps: {
                onChange: (newProduct) => onProductEdit(newProduct),
                product: product.product,
            }
        })
    }
    return (
        <div className={styles['container']}>
            <div className={styles['data-container']}>
                <div


                    className={styles['image-container']}>
                    <Image
                        flex={1}
                        radius={rem(10)}
                        fit={"cover"}
                        src={product.product.imageUrl}
                    />
                </div>
                <div className={styles['attributes-container']}>
                    <Title order={3}>{product.product.name}</Title>
                    {/*<Spoiler maxHeight={0} showLabel={"Показать характеристики"} hideLabel={"Скрыть"}>*/}

                        {Object.entries(product.product).map(([key, value]) => {
                            const fieldName = ProductFieldNames[key as keyof ProductSchema];
                            if (!fieldName || isNil(value) || value === '') return;
                            return (<Text key={fieldName}>{fieldName}: {value.toString()} </Text>)
                        })}
                        <Text>Штрихкоды: {product.product.barcodes.join(', ')}</Text>
                    {/*</Spoiler>*/}

                </div>
                <Box/>
                <NumberInput
                    mt={rem(10)}
                    disabled={isLocked}
                    suffix={" шт."}
                    value={product.quantity}
                    onChange={event => isNumber(event) && onQuantityChange(event)}
                    placeholder={"Введите количество товара"}
                />
            </div>

            <div className={styles['services-container']}>
                <ProductServicesTable
                    onKitAdd={onKitAddClick}
                    onCopyServices={() => onCopyServices && onCopyServices(product)}
                    items={product.services}
                    quantity={product.quantity}
                    onCreate={onServiceCreate}
                    onDelete={onServiceDelete}
                    onChange={onServiceChange}
                />
                <Flex
                    mt={"auto"}
                    ml={"auto"}
                    gap={rem(10)}
                >
                    <Tooltip

                        onClick={onPrintBarcodeClick}
                        label="Печать штрихкода">
                        <ActionIcon

                            variant={"default"}>
                            <IconBarcode/>
                        </ActionIcon>
                    </Tooltip>
                    <Tooltip
                        onClick={onProductEditClick}
                        label="Редактировать товар">
                        <ActionIcon

                            variant={"default"}>
                            <IconEdit/>
                        </ActionIcon>
                    </Tooltip>
                    <Tooltip onClick={onDeleteClick} label="Удалить товар">
                        <ActionIcon
                            disabled={isLocked}
                            variant={"default"}
                        >
                            <IconTrash/>
                        </ActionIcon>
                    </Tooltip>
                </Flex>
            </div>
        </div>
    )
}

export default ProductView;