import React, { useState, useCallback, useEffect } from 'react';
import { UdpCard } from '../../UI/fluent-web-components/UdpCard';
import { UdpAutocomplete } from '../../UI/fluent-web-components/UdpAutocomplete';
import { UdpButton } from '../../UI/fluent-web-components/UdpButton';
import { apiMutate } from '../../utilities/useAxiosMutate';
import { useHandleAxiosSnackbar } from '../../utilities/apiHelpers';
import { UdpDrawer } from '../../UI/fluent-web-components/UdpDrawer';
import { UdpFileInput } from '../../UI/fluent-web-components/UdpFileInput';
import FileImportMappingWizard from './FileImportMappingWizard';
import { usePromotedMethodEntity } from '../../hooks/usePromotedMethodEntity';
import { executeQueryAdHoc } from '../utilities/methodUtils';
import { useUser } from '../../utilities/auth/useUser';
import { FileImportConfigCard } from './FileImportConfigCard';
import { ConfigService } from '../../configService';
export const ImportDataFromFileMapping = (props) => {
    var _a, _b;
    const { onImportSuccess, onImportFail, verifyRequiredFields = true } = props;
    const user = useUser();
    const [selectedFileMapping, setSelectedFileMapping] = useState();
    const [udpImportMappingData, setUdpImportMappingData] = useState();
    const [newFileMappingSidesheetOpen, setNewFileMappingSidesheetOpen] = useState(false);
    const [fileObject, setFileObject] = useState();
    const [fileItems, setFileItems] = useState([]);
    const [isLoading, setIsLoading] = useState(false);
    const { handleErrorSnackbar, handleSuccessSnackbar } = useHandleAxiosSnackbar();
    const { data: udpFileImportMappingEntity } = usePromotedMethodEntity('UdpFileImportMapping', true);
    // React Compiler narrows property accesses inside closures into cache-key
    // checks that run on every render and drop optional chaining. Reading from
    // an always-defined alias keeps those checks safe before a mapping is picked.
    const fm = selectedFileMapping !== null && selectedFileMapping !== void 0 ? selectedFileMapping : {};
    const executeImportDataFromFile = async (data) => apiMutate(ConfigService.productV1ApiUrl, `${fm.objectInfoSanitizedName}/fileImportMapping`, {
        method: 'post'
    }, { data });
    const searchFileImportMappingData = useCallback(async () => {
        var _a, _b, _c, _d;
        if ((_a = udpFileImportMappingEntity === null || udpFileImportMappingEntity === void 0 ? void 0 : udpFileImportMappingEntity.unityBaseSearchMethod) === null || _a === void 0 ? void 0 : _a.apiMethodId) {
            const res = await executeQueryAdHoc({
                data: {
                    eagerLoad: true,
                    pageSize: 200,
                    filterElements: []
                }
            }, (_b = udpFileImportMappingEntity === null || udpFileImportMappingEntity === void 0 ? void 0 : udpFileImportMappingEntity.unityBaseSearchMethod) === null || _b === void 0 ? void 0 : _b.apiMethodId);
            if (((_c = res === null || res === void 0 ? void 0 : res.data) === null || _c === void 0 ? void 0 : _c.pageList.length) > 0) {
                setUdpImportMappingData((_d = res === null || res === void 0 ? void 0 : res.data) === null || _d === void 0 ? void 0 : _d.pageList);
            }
        }
    }, [(_a = udpFileImportMappingEntity === null || udpFileImportMappingEntity === void 0 ? void 0 : udpFileImportMappingEntity.unityBaseSearchMethod) === null || _a === void 0 ? void 0 : _a.apiMethodId]);
    useEffect(() => {
        searchFileImportMappingData();
    }, [searchFileImportMappingData]);
    const handleImportDataFromFile = async () => {
        setIsLoading(true);
        const file = fileObject;
        const blob = new Blob([file], { type: file.type });
        const formData = new FormData();
        formData.append('file', blob, file.name);
        formData.append('tenantId', user === null || user === void 0 ? void 0 : user.currentTenantId);
        formData.append('name', fm.name);
        formData.append('objectInfoSanitizedName', fm.objectInfoSanitizedName);
        formData.append('fileImportType', fm.fileImportType);
        formData.append('mapping', fm.mapping);
        formData.append('properties', fm.properties);
        formData.append('id', fm.id);
        const response = await executeImportDataFromFile(formData).catch((res) => {
            setIsLoading(false);
            handleErrorSnackbar(res);
            onImportFail();
        });
        if ((response === null || response === void 0 ? void 0 : response.status) === 201) {
            handleSuccessSnackbar('Imported Data');
            setIsLoading(false);
            onImportSuccess && onImportSuccess();
        }
    };
    const getFileMappingOptionlabel = (option) => {
        var _a;
        return `${option.name} (${(_a = option === null || option === void 0 ? void 0 : option.udpFileImportMappingUdpFileImportType) === null || _a === void 0 ? void 0 : _a.extension})`;
    };
    const handleAddFileToUpload = (e) => {
        var _a;
        const items = e.target.value;
        setFileItems(items);
        setFileObject((_a = items.find(item => item.kind === 'pending')) === null || _a === void 0 ? void 0 : _a.file);
    };
    return (React.createElement(React.Fragment, null, React.createElement(UdpCard, { width: "100%" }, React.createElement("div", { style: { display: 'flex' } }, React.createElement(UdpAutocomplete, { name: 'fileMapping', label: "File Mapping", onChange: (e) => setSelectedFileMapping(e.target.value), options: udpImportMappingData, optionLabel: getFileMappingOptionlabel, optionValue: "id", value: selectedFileMapping, required: true, optionGroup: (option) => {
            var _a;
            return (_a = option === null || option === void 0 ? void 0 : option.udpFileImportMappingUdpObjectInfo) === null || _a === void 0 ? void 0 : _a.sanitizedName;
        } })), selectedFileMapping && (React.createElement(UdpFileInput, { value: fileItems, onChange: handleAddFileToUpload, accept: ".csv,.txt,.xlsx,.json", maxFiles: 1 })), React.createElement("div", { style: {
            display: 'flex',
            flexDirection: 'row',
            gap: 5,
            float: 'right',
            marginTop: 10
        } }, React.createElement(UdpButton, { onClick: () => setNewFileMappingSidesheetOpen(true), appearance: "outline" }, "Create New Mappin"), React.createElement(UdpButton, { appearance: "primary", onClick: handleImportDataFromFile, loading: isLoading, disabled: !fileObject }, "Import Dat")), React.createElement(UdpDrawer, { drawerTitle: "Create New File Mapping", open: newFileMappingSidesheetOpen, onDrawerClose: () => setNewFileMappingSidesheetOpen(false), drawerWidth: '60%' }, React.createElement(FileImportMappingWizard, { refetchMappings: searchFileImportMappingData, setNewFileMappingSidesheetOpen: setNewFileMappingSidesheetOpen, verifyRequiredFields: verifyRequiredFields }))), React.createElement("div", { style: { marginTop: 10 } }, React.createElement(FileImportConfigCard, { fileMappingRecord: selectedFileMapping, domain: (_b = fm.udpFileImportMappingUdpObjectInfo) === null || _b === void 0 ? void 0 : _b.sanitizedName.replace(/([A-Z])/g, ' $1').trim() }))));
};
//# sourceMappingURL=ImportDataFromFileMapping.js.map