var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
import React, { useCallback, useState, useMemo, useRef, useEffect, useLayoutEffect } from 'react';
import { TextField, Button, LinearProgress, IconButton } from '@material-ui/core';
import { Form } from '../../../utilities/form/Form';
import { Field } from '../../../utilities/form/Field';
import { SubmitButton } from '../../../utilities/form/SubmitButton';
import { SideSheet } from '../../../UI/surfaces/SideSheet';
import { AmbientGridTemplate } from '../../../UI/templates/deprecated/AmbientGridTemplate/AmbientGridTemplate';
import { useActionState } from '../../../hooks/useActions';
import { useTranslation } from 'react-i18next';
import { ActionsRenderer } from '../../../UI/templates/ui/renderers/ActionsRenderer';
import { FluentCheckbox } from '../../../UI/inputs/checkbox/FluentCheckbox';
import { UnityFluentIcon } from '../../../utilities/iconLibrary/UnityFluentIcon';
import { findAllParentIds, getIconFromName } from '../../../utilities/tree/TreeUtilities';
import { getUnityIconFromName } from '../../../utilities/iconLibrary/UnityIconLibrary';
import IconLibrary from '../../../utilities/iconLibrary/IconLibrary';
import { apiMutate } from '../../../utilities/useAxiosMutate';
import { FormButtons } from '../../../utilities/form';
import { useHandleAxiosSnackbar } from '../../../utilities/apiHelpers';
import { ConfigService } from '../../../configService';
const UdpVerticalManagementSidesheet = (props) => {
    const { selectedVertical, environment, associatedProducts, isEdit, deleteVertical, open, selectedCatalog, closeSidesheet, onSubmit } = props, sheetProps = __rest(props, ["selectedVertical", "environment", "associatedProducts", "isEdit", "deleteVertical", "open", "selectedCatalog", "closeSidesheet", "onSubmit"]);
    const { t } = useTranslation();
    const [loading, setLoading] = useState(false);
    const actionState = useActionState();
    const [displayedIcon, setDisplayedIcon] = useState({
        name: 'StatusCircleQuestionMarkIcon',
        color: '',
        type: ''
    });
    const [products, setProducts] = useState([]);
    const [openIconLibrary, setOpenIconLibrary] = useState(false);
    const [selectedProductIds, setSelectedProductIds] = useState([]);
    const [checkboxValues, setCheckboxValues] = useState([]);
    const [submitButtonDisabled, setSubmitButtonDisabled] = useState(true);
    const selectedProductIdsRef = useRef();
    selectedProductIdsRef.current = selectedProductIds;
    const displayedIconRef = useRef();
    displayedIconRef.current = displayedIcon;
    const selectedVerticalRef = useRef();
    selectedVerticalRef.current = selectedVertical;
    const formRef = useRef();
    const nameRef = useRef();
    const { handleErrorSnackbar, handleSuccessSnackbar } = useHandleAxiosSnackbar();
    const CheckBoxRenderer = ({ onChange, value, id, defaultChecked }) => {
        const isAssociatedToVertical = useCallback((productId) => {
            if (!isEdit)
                return false;
            for (let product of associatedProducts) {
                if (product.productId === productId &&
                    product.verticalId === selectedVerticalRef.current.verticalId) {
                    return true;
                }
            }
            // console.log(selectedVerticalRef.current.icon)
            const icon = getIconFromName(selectedVerticalRef.current.icon);
            // console.log("🚀 ~ file: UdpVerticalManagementSidesheet.jsx:81 ~ isAssociatedToVertical ~ icon:", icon)
            return false;
        }, [associatedProducts, selectedVerticalRef]);
        const handleCheckboxChange = (e) => {
            if (e.target.checked) {
                setSelectedProductIds((prevState) => [...prevState, id]);
            }
            else {
                setSelectedProductIds((prevState) => prevState.filter((item) => item !== id));
            }
        };
        return (React.createElement(FluentCheckbox
        // checked={value}
        , { 
            // checked={value}
            defaultChecked: isAssociatedToVertical(id), onChange: handleCheckboxChange, aria: "column-active" }));
    };
    // const actionList = useMemo(
    //   () => [
    //     {
    //       id: 1, // Must be unique
    //       title: t('Edit'),
    //       icon: EditIcon,
    //       onClick: handleEditPage,
    //       disabled: false
    //     },
    //     {
    //       id: 2, // Must be unique
    //       title: t('Delete'),
    //       icon: DeleteIcon,
    //       onClick: handleDelete,
    //       disabled: false
    //     }
    //   ],
    //   [t, handleEditPage, handleDelete]
    // );
    const gridOptions = useMemo(() => ({
        frameworkComponents: {
            actionsRenderer: ActionsRenderer,
            checkboxRenderer: CheckBoxRenderer
        },
        columnDefs: [
            {
                headerName: '',
                field: 'select',
                cellRenderer: 'checkboxRenderer',
                cellRendererParams: (params) => ({
                    // onChange: onChange,
                    // value: checked[params.data.productId] || false,
                    id: params.data.productId
                })
            },
            {
                headerName: t('Product Name'),
                field: 'name',
                minWidth: 200
            }
        ]
    }), [isEdit, selectedVertical, associatedProducts]);
    const executeMutation = useCallback(async (endpoint, method, data) => apiMutate(ConfigService.uemV1ApiUrl, endpoint, {
        method: method || 'post'
    }, data), []);
    const getProducts = useCallback(async (data) => {
        setLoading(true);
        const response = await executeMutation('uem', 'post', data);
        if ((response === null || response === void 0 ? void 0 : response.status) === 200) {
            setProducts(response === null || response === void 0 ? void 0 : response.data);
        }
        setLoading(false);
    }, [executeMutation, setProducts]);
    const createVertical = useCallback(async (data) => {
        setLoading(true);
        const response = await executeMutation('vertical/uemCreate', 'post', data);
        if ((response === null || response === void 0 ? void 0 : response.status) === 201) {
            closeSidesheet();
            handleSuccessSnackbar('Vertical Created Successfully');
        }
        else {
            handleErrorSnackbar('Something went wrong');
        }
        setLoading(false);
    }, [executeMutation]);
    const updateVertical = useCallback(async (data) => {
        setLoading(true);
        const response = await executeMutation(`vertical/${selectedVertical.verticalId}/uemUpdate`, 'put', data);
        if ((response === null || response === void 0 ? void 0 : response.status) === 204) {
            closeSidesheet();
            handleSuccessSnackbar('Vertical Updated Successfully');
        }
        else {
            handleErrorSnackbar('Something went wrong');
        }
        setLoading(false);
    }, [selectedVertical, executeMutation]);
    const handleSubmit = useCallback((values) => {
        setLoading(true);
        const products = selectedProductIdsRef.current.map((productId) => ({
            productId
        }));
        !isEdit
            ? createVertical({
                data: {
                    name: values.name,
                    products: products,
                    icon: displayedIconRef === null || displayedIconRef === void 0 ? void 0 : displayedIconRef.current.name,
                    EnvironmentId: environment.environmentId,
                    apiPath: 'api/v1/vertical/uemCreate'
                }
            })
            : updateVertical({
                data: {
                    name: values.name,
                    products: products,
                    icon: displayedIconRef === null || displayedIconRef === void 0 ? void 0 : displayedIconRef.current.name,
                    EnvironmentId: environment.environmentId,
                    apiPath: `api/v1/vertical/${selectedVertical.verticalId}/uemUpdate`
                }
            });
    }, [
        isEdit,
        createVertical,
        environment,
        updateVertical,
        selectedVertical,
        selectedProductIdsRef
    ]);
    useEffect(() => {
        if (environment && getProducts) {
            if (environment.environmentId) {
                const data = {
                    data: {
                        customerId: null,
                        environmentId: environment.environmentId,
                        apiPath: `tenantService/api/v2/product`
                    }
                };
                getProducts(data);
            }
        }
    }, [environment, getProducts]);
    useEffect(() => {
        if (selectedVertical) {
            const associatedProductIds = selectedVertical.verticalProductVertical.map((product) => product.productId);
            setSelectedProductIds((prevState) => [
                ...prevState,
                ...associatedProductIds
            ]);
        }
    }, [selectedVertical, setSelectedProductIds]);
    const setDisplayedIconCallback = useCallback(() => {
        setDisplayedIcon({
            name: isEdit && (selectedVertical === null || selectedVertical === void 0 ? void 0 : selectedVertical.icon)
                ? selectedVertical === null || selectedVertical === void 0 ? void 0 : selectedVertical.icon
                : 'StatusCircleQuestionMarkIcon'
        });
    }, [selectedVertical, isEdit]);
    useEffect(() => {
        setDisplayedIconCallback();
    }, [open]);
    const closeIconLibrary = () => {
        setOpenIconLibrary(false);
    };
    const onOpenLibrary = () => {
        setOpenIconLibrary(true);
    };
    const handleIconSelect = (icon) => {
        const updateddisplayedIcon = Object.assign({}, props.displayedIcon);
        updateddisplayedIcon.name = icon.id;
        updateddisplayedIcon.type = icon.type || null;
        setDisplayedIcon(updateddisplayedIcon);
        closeIconLibrary();
    };
    const initialValues = useMemo(() => {
        return {
            name: isEdit ? selectedVertical === null || selectedVertical === void 0 ? void 0 : selectedVertical.name : ''
        };
    }, [associatedProducts, selectedVertical, isEdit]);
    return (React.createElement(React.Fragment, null, React.createElement(SideSheet, { open: open, onClose: () => closeSidesheet(), width: 400, title: props.title }, React.createElement(Form, { ref: formRef, onSubmit: handleSubmit, initialValues: initialValues }, React.createElement("div", { style: { display: 'flex' } }, React.createElement(Field, { ref: nameRef, component: TextField, label: t('Name'), id: "name", name: "name", variant: "outlined", size: "small", required: true, style: { marginTop: 8 } }), React.createElement(IconButton, { onClick: onOpenLibrary }, displayedIcon && (React.createElement(UnityFluentIcon, { type: displayedIcon === null || displayedIcon === void 0 ? void 0 : displayedIcon.type, icon: (displayedIcon === null || displayedIcon === void 0 ? void 0 : displayedIcon.type) === 'unity'
            ? getUnityIconFromName(displayedIcon === null || displayedIcon === void 0 ? void 0 : displayedIcon.name)
            : getIconFromName(displayedIcon === null || displayedIcon === void 0 ? void 0 : displayedIcon.name) })))), React.createElement(AmbientGridTemplate, Object.assign({ data: products, title: t('Products'), loading: loading, height: 'calc(100vh - 300px)', hideGroupTab: true, hideColumnTab: true, disablePagination: true, hideFitGrid: true, hideExpandGrid: true, hideExportGrid: true, hideRemoveFilters: true, hideFilterTab: true }, gridOptions)), React.createElement(FormButtons, null, React.createElement(SubmitButton, { variant: "contained", color: "secondary", marginTop: '50px', disabled: false, disablePristine: false }, t(isEdit ? 'Update' : 'Create'))), loading && React.createElement(LinearProgress, null))), React.createElement(SideSheet, { open: openIconLibrary, onClose: closeIconLibrary, title: t('Icon Library'), width: '100%', anchor: "bottom" }, React.createElement(IconLibrary, { addItem: handleIconSelect, selectedIconName: displayedIcon === null || displayedIcon === void 0 ? void 0 : displayedIcon.name, title: t('Select Icon') }))));
};
export default UdpVerticalManagementSidesheet;
//# sourceMappingURL=UdpVerticalManagementSidesheet.js.map