import React, { useState, useMemo, useCallback } from 'react';
import { ClientSideUdpGrid } from '../../../UI/templates/newGrid';
import { UdpDialog } from '../../../UI/fluent-web-components/UdpDialog';
import { UdpButton } from '../../../UI/fluent-web-components/UdpButton';
import { UdpText } from '../../../UI/fluent-web-components/UdpText';
import { useLookups } from '../../lookups/useLookups';
import { LookupCreationSheet } from '../../lookups/LookupCreationSheet';
import { useApiCatalog } from '../../../hooks/useApiCatalog';
import { useAxiosGet } from '../../../utilities/useAxiosGet';
import { useUser } from '../../../utilities/auth/useUser';
import { ConfigService } from '../../../configService';
import { LookupTypeId } from 'udp-stencil-component-library';
export const UdpLookupManagementPage = ({ productId }) => {
    var _a;
    var _b;
    const user = useUser();
    const tenantId = user === null || user === void 0 ? void 0 : user.currentTenantId;
    const resolvedProductId = productId !== null && productId !== void 0 ? productId : ConfigService.config.UNITY_PRODUCT_ID;
    const [{ data: productCatalog }] = useAxiosGet(ConfigService.integrationV1ApiUrl, `tenantProductApiCatalogBase/tenant/${tenantId}/product/${resolvedProductId}`, {}, !tenantId || !resolvedProductId, true);
    const apiCatalogId = productCatalog === null || productCatalog === void 0 ? void 0 : productCatalog.apiCatalogId;
    const { lookups, loading: lookupsLoading, refetch, methodStatus, createLookup, updateLookup, deleteLookup, fetchColumns, createLookupColumn, updateLookupColumn, fetchValues, createLookupValue, deleteLookupValue } = useLookups(apiCatalogId, productId);
    const [loading, setLoading] = useState(false);
    const [sheetOpen, setSheetOpen] = useState(false);
    const { data: catalogData } = useApiCatalog(sheetOpen ? apiCatalogId : undefined);
    const catalogObjectList = (_b = (_a = catalogData === null || catalogData === void 0 ? void 0 : catalogData.ctlg) === null || _a === void 0 ? void 0 : _a.catalogObjectList) !== null && _b !== void 0 ? _b : [];
    const [editLookup, setEditLookup] = useState(null);
    const [deleteTarget, setDeleteTarget] = useState(null);
    const [deleting, setDeleting] = useState(false);
    const handleRefresh = useCallback(() => {
        setLoading(true);
        refetch();
    }, [refetch]);
    const handleCreate = useCallback(() => {
        setEditLookup(null);
        setSheetOpen(true);
    }, []);
    const handleEdit = useCallback((_, params) => {
        setEditLookup(params === null || params === void 0 ? void 0 : params.data);
        setSheetOpen(true);
    }, []);
    const handleSheetClose = useCallback(() => {
        setSheetOpen(false);
        setEditLookup(null);
    }, []);
    const handleLookupCreatedOrUpdated = useCallback(() => {
        refetch();
    }, [refetch]);
    const handleDeleteConfirm = useCallback(async () => {
        if (!deleteTarget)
            return;
        setDeleting(true);
        try {
            await deleteLookup(deleteTarget);
            setDeleteTarget(null);
            refetch();
        }
        finally {
            setDeleting(false);
        }
    }, [deleteTarget, deleteLookup, refetch]);
    const statusConfig = useMemo(() => ({
        true: 'success',
        false: 'secondary'
    }), []);
    const columnDefs = useMemo(() => [
        { headerName: 'Name', field: 'name' },
        {
            headerName: 'Description',
            field: 'description'
        },
        {
            headerName: 'Domain',
            field: 'domainName',
            valueFormatter: (params) => {
                if (!params.value)
                    return '';
                const parts = params.value.split('.');
                return parts[parts.length - 1];
            }
        },
        {
            headerName: 'Type',
            field: 'typeId',
            cellRenderer: 'statusRenderer',
            cellRendererParams: {
                getStatusConfig: (params) => {
                    if (params.value === LookupTypeId.Domain)
                        return { label: 'Domain', color: 'warning' };
                    if (params.value === LookupTypeId.Lookup)
                        return { label: 'Virtual', color: 'info' };
                    return null;
                }
            }
        },
        { headerName: 'Key Name', field: 'keyName' },
        { headerName: 'Value Name', field: 'valueName' },
        {
            field: 'actions',
            cellRenderer: 'actionsRenderer',
            cellRendererParams: {
                actionList: [
                    {
                        id: 1,
                        iconName: 'edit',
                        title: 'Edit',
                        handleOnClick: handleEdit
                    },
                    {
                        id: 2,
                        iconName: 'delete',
                        title: 'Delete',
                        handleOnClick: (_, params) => setDeleteTarget(params === null || params === void 0 ? void 0 : params.data)
                    }
                ]
            }
        }
    ], [handleEdit]);
    const gridHeaderConfig = useMemo(() => ({
        title: 'Lookups',
        primaryActionButton: {
            label: 'Create Lookup',
            iconName: 'add',
            onClick: handleCreate
        }
    }), [handleCreate]);
    const gridFunctions = useMemo(() => [
        {
            name: 'agGridRefreshData',
            params: {
                onRefreshStart: handleRefresh,
                onRefreshComplete: () => setLoading(false)
            }
        },
        { name: 'quickFilter' }
    ], [handleRefresh]);
    return (React.createElement(React.Fragment, null, React.createElement(ClientSideUdpGrid, { rowData: lookups !== null && lookups !== void 0 ? lookups : [], loading: loading || lookupsLoading, columnDefs: columnDefs, gridHeaderConfig: gridHeaderConfig, gridFunctions: gridFunctions, gridOptions: { pagination: true } }), React.createElement(LookupCreationSheet, { open: sheetOpen, onClose: handleSheetClose, lookup: editLookup, onCreateLookup: createLookup, onCreateLookupColumn: createLookupColumn, onCreateLookupValue: createLookupValue, onUpdateLookup: updateLookup, onUpdateLookupColumn: updateLookupColumn, onDeleteLookupValue: deleteLookupValue, fetchColumns: fetchColumns, fetchValues: fetchValues, onLookupCreated: handleLookupCreatedOrUpdated, catalogObjectList: catalogObjectList, lookupMethodStatus: methodStatus }), React.createElement(UdpDialog, { open: !!deleteTarget, dialogTitle: "Delete Lookup", onDialogClose: () => setDeleteTarget(null) }, React.createElement(UdpText, null, "Are you sure you want to delete &ldquo;", deleteTarget === null || deleteTarget === void 0 ? void 0 : deleteTarget.name, "&rdquo; This action cannot be undone"), React.createElement(UdpButton, { appearance: "outline", onClick: () => setDeleteTarget(null), slot: "action" }, "Cance"), React.createElement(UdpButton, { appearance: "primary", onClick: handleDeleteConfirm, loading: deleting, slot: "action" }, "Delet"))));
};
//# sourceMappingURL=UdpLookupManagementPage.js.map