import { FC } from "react";
import { isNumber } from "lodash";
import {
    Flex,
    Image,
    NumberInput,
    Stack,
    Textarea,
    Title,
} from "@mantine/core";
import { useDebouncedCallback } from "@mantine/hooks";
import { modals } from "@mantine/modals";
import {
    addKitToDealProduct,
    DealProductSchema,
    duplicateProductServices,
    ServicesKitSchema,
} from "@/lib/client";
import { useFulfillmentBaseContext } from "@/modules/dealModularEditorTabs/FulfillmentBase/shared/contexts/FulfillmentBaseContext";
import ProductFieldsList from "@/modules/dealModularEditorTabs/FulfillmentBase/desktop/components/ProductView/components/ProductFieldsList";
import ProductViewActions from "@/modules/dealModularEditorTabs/FulfillmentBase/desktop/components/ProductView/components/ProductViewActions";
import { ServiceType } from "@/modules/dealModularEditorTabs/FulfillmentBase/shared/types/service";
import ProductServicesTable from "./components/ProductServicesTable";
import styles from "../../../FulfillmentBase.module.css";

type Props = {
    dealProduct: DealProductSchema;
};

const ProductView: FC<Props> = ({ dealProduct }) => {
    const { dealProductsCrud, deal, dealProductsList } =
        useFulfillmentBaseContext();

    const debouncedOnChange = useDebouncedCallback(
        (newValues: Partial<DealProductSchema>) => {
            dealProductsCrud.onUpdate(
                dealProduct.dealId,
                dealProduct.productId,
                {
                    ...dealProduct,
                    ...newValues,
                }
            );
        },
        200
    );

    const duplicateServices = (
        sourceDealProduct: DealProductSchema,
        targetDealProducts: DealProductSchema[]
    ) => {
        duplicateProductServices({
            body: {
                dealId: deal.id,
                sourceDealProductId: sourceDealProduct.productId,
                targetDealProductIds: targetDealProducts.map(p => p.productId),
            },
        })
            .then(() => dealProductsList.refetch())
            .catch(err => console.error(err));
    };

    const onDuplicateServices = (sourceDealProduct: DealProductSchema) => {
        modals.openContextModal({
            modal: "duplicateServicesModal",
            title: "Дублирование услуг",
            size: "lg",
            innerProps: {
                dealProducts: dealProductsList.dealProducts,
                sourceDealProduct,
                duplicateServices,
            },
            withCloseButton: false,
        });
    };

    const onServicesKitAdd = (servicesKit: ServicesKitSchema) => {
        addKitToDealProduct({
            body: {
                dealId: dealProduct.dealId,
                productId: dealProduct.productId,
                kitId: servicesKit.id,
            },
        })
            .then(() => dealProductsList.refetch())
            .catch(err => console.error(err));
    };

    const onAddKitClick = () => {
        modals.openContextModal({
            modal: "servicesKitSelectModal",
            innerProps: {
                onSelect: onServicesKitAdd,
                serviceType: ServiceType.PRODUCT_SERVICE,
            },
            withCloseButton: false,
        });
    };

    return (
        <Flex
            align={"start"}
            direction={"row"}
            className={styles.container}
            gap={"sm"}>
            <Stack
                flex={2}
                gap={"sm"}>
                {!dealProduct.product && (
                    <Image
                        flex={1}
                        radius={"md"}
                        fit={"cover"}
                        // src={dealProduct.product.imageUrl}
                    />
                )}
                <Title order={3}>{dealProduct.product.name}</Title>
                <ProductFieldsList product={dealProduct.product} />
                {/*<Text>*/}
                {/*    Штрихкоды:*/}
                {/*{value.product.barcodes.join(", ")}*/}
                {/*</Text>*/}
                <NumberInput
                    suffix={" шт."}
                    value={dealProduct.quantity}
                    onChange={quantity =>
                        isNumber(quantity) && debouncedOnChange({ quantity })
                    }
                    placeholder={"Введите количество товара"}
                    min={1}
                    allowNegative={false}
                />
                <Textarea
                    defaultValue={dealProduct.comment}
                    onChange={event =>
                        debouncedOnChange({
                            comment: event.currentTarget.value,
                        })
                    }
                    rows={4}
                    placeholder={"Комментарий"}
                />
            </Stack>
            <Stack flex={5}>
                <ProductServicesTable
                    dealProduct={dealProduct}
                    onDuplicateServices={() => onDuplicateServices(dealProduct)}
                    onKitAdd={onAddKitClick}
                />
                <ProductViewActions dealProduct={dealProduct} />
            </Stack>
        </Flex>
    );
};

export default ProductView;
