import React, { useMemo, useState, useCallback, useEffect } from 'react';
import { useUser } from '../../utilities/auth/useUser';
import { useAxiosGet } from '../../utilities/useAxiosGet';
import { UdpCard } from '../../UI/fluent-web-components/UdpCard';
import { UdpAutocomplete } from '../../UI/fluent-web-components/UdpAutocomplete';
import { usePromotedMethodEntity } from '../../hooks/usePromotedMethodEntity';
import { executeQueryAdHoc } from '../utilities/methodUtils';
import { Form } from '../../utilities/form';
import { Field } from '../../utilities/form';
import { AmbientStepper } from '../../UI/inputs/menus/AmbientStepper/AmbientStepper';
import { apiMutate } from '../../utilities/useAxiosMutate';
import { useHandleAxiosSnackbar } from '../../utilities/apiHelpers';
import { UdpFileInput } from '../../UI/fluent-web-components/UdpFileInput';
import { UdpDropdown } from '../../UI/fluent-web-components';
import { UdpText } from '../../UI/fluent-web-components/UdpText';
import { UdpButton } from '../../UI/fluent-web-components/UdpButton';
import { UdpTextInput } from '../../UI/fluent-web-components/UdpTextInput';
import { UdpDivider } from '../../UI/fluent-web-components/UdpDivider';
import { UdpIcon } from '../../UI/fluent-web-components/UdpIcon';
import { handleExcelFileUpload, handleJsonFileUpload, handleTextFileUpload } from './fileUtils';
import { FileImportConfigCard } from './FileImportConfigCard';
import { getSanitizedName } from '../../utilities/entities/entityUtilities';
import { ConfigService } from '../../configService';
const FileImportMappingWizard = (props) => {
    const { refetchMappings, setNewFileMappingSidesheetOpen, verifyRequiredFields } = props;
    const user = useUser();
    const [importHeaderData, setImportHeaderData] = useState();
    const [udpObjectList, setUdpObjectList] = useState();
    const [selectedDomain, setSelectedDomain] = useState();
    const [selectedFileType, setSelectedFileType] = useState();
    const [fileObject, setFileObject] = useState();
    const [fileItems, setFileItems] = useState([]);
    const [fileImportMappingObject, setFileImportMappingObject] = useState({});
    const [activeStep, setActiveStep] = useState(0);
    const [showIndexNumbers, setShowIndexNumbers] = useState(false);
    const [errorText, setErrorText] = useState('');
    const { handleErrorSnackbar, handleSuccessSnackbar } = useHandleAxiosSnackbar();
    const executeCreateFileMapping = useCallback(async (data) => apiMutate(ConfigService.productV1ApiUrl, `UdpFileImportMapping`, {
        method: 'post'
    }, { data }), []);
    const { data: udpObjectEntity } = usePromotedMethodEntity('UdpObjectInfo', true);
    const [{ data: allowedFileTypesData }, refetchAllowedFileTypes] = useAxiosGet(ConfigService.productV1ApiUrl, `UdpFileImportType`, {}, false);
    const searchUdpObjectData = useCallback(async () => {
        var _a, _b, _c, _d;
        if (((_a = udpObjectEntity === null || udpObjectEntity === void 0 ? void 0 : udpObjectEntity.unityBaseSearchMethod) === null || _a === void 0 ? void 0 : _a.apiMethodId) && (user === null || user === void 0 ? void 0 : user.id)) {
            const sapUserRes = await executeQueryAdHoc({
                data: {
                    eagerLoad: true,
                    pageSize: 200,
                    filterElements: []
                }
            }, (_b = udpObjectEntity === null || udpObjectEntity === void 0 ? void 0 : udpObjectEntity.unityBaseSearchMethod) === null || _b === void 0 ? void 0 : _b.apiMethodId);
            if (((_c = sapUserRes === null || sapUserRes === void 0 ? void 0 : sapUserRes.data) === null || _c === void 0 ? void 0 : _c.pageList.length) > 0) {
                setUdpObjectList((_d = sapUserRes === null || sapUserRes === void 0 ? void 0 : sapUserRes.data) === null || _d === void 0 ? void 0 : _d.pageList);
            }
        }
    }, [udpObjectEntity, user]);
    const filterCatalogObjectList = useMemo(() => {
        return udpObjectList;
    }, [udpObjectList]);
    const getNameFormattedOptionLabel = (option) => {
        return option === null || option === void 0 ? void 0 : option.name.replace(/([A-Z])/g, ' $1').trim();
    };
    const getNameOptionLabel = (option) => {
        return option === null || option === void 0 ? void 0 : option.name;
    };
    const handleFileUpload = async (properties) => {
        let result;
        if (selectedFileType.extension === '.csv' ||
            selectedFileType.extension === '.txt') {
            result = await handleTextFileUpload(fileObject, properties);
        }
        else if (selectedFileType.extension === '.xlsx') {
            result = await handleExcelFileUpload(fileObject, properties);
        }
        else if (selectedFileType.extension === '.json') {
            result = await handleJsonFileUpload(fileObject, properties);
        }
        setImportHeaderData(result === null || result === void 0 ? void 0 : result.headers);
    };
    useEffect(() => {
        searchUdpObjectData();
    }, [searchUdpObjectData]);
    const handleCreateNewFieldMapping = async (values) => {
        const response = await executeCreateFileMapping({
            name: values.name,
            objectInfoSanitizedName: getSanitizedName(selectedDomain === null || selectedDomain === void 0 ? void 0 : selectedDomain.name),
            fileImportType: selectedFileType === null || selectedFileType === void 0 ? void 0 : selectedFileType.id,
            mapping: JSON.stringify(fileImportMappingObject === null || fileImportMappingObject === void 0 ? void 0 : fileImportMappingObject.mapping),
            properties: JSON.stringify(fileImportMappingObject === null || fileImportMappingObject === void 0 ? void 0 : fileImportMappingObject.properties)
        }).catch((res) => {
            handleErrorSnackbar(res);
        });
        if ((response === null || response === void 0 ? void 0 : response.status) === 201) {
            handleSuccessSnackbar('Created Mapping');
            refetchMappings();
            setNewFileMappingSidesheetOpen(false);
        }
    };
    const handleUpdateFieldMapping = (values) => {
        var _a;
        let valid = true;
        (_a = selectedDomain === null || selectedDomain === void 0 ? void 0 : selectedDomain.objectFieldInfo) === null || _a === void 0 ? void 0 : _a.forEach((option) => {
            if (!option.dataType.endsWith('?') &&
                !option.isPrimaryKey &&
                !option.udpType) {
                if (!Object.entries(values).some((obj) => obj[1].businessObjectKey === option.businessObjectKey)) {
                    if (verifyRequiredFields) {
                        valid = false;
                    }
                }
            }
        });
        if (!valid) {
            setErrorText('All required Udp fields must have a mapping');
            return;
        }
        const filteredMappings = Object.entries(values)
            .filter(([key, value]) => value !== null)
            .reduce((acc, [key, value]) => {
            acc[key] = value;
            return acc;
        }, {});
        const mappedFieldIndexes = Object.keys(filteredMappings).map((key) => parseInt(key.split('udpFieldMapping')[1], 10));
        const fieldMappings = Object.values(filteredMappings).map((selectedUdpField, index) => {
            return {
                udpField: selectedUdpField.name,
                importFileField: !showIndexNumbers
                    ? importHeaderData[mappedFieldIndexes[index]]
                    : null,
                headerIndex: !showIndexNumbers ? -1 : mappedFieldIndexes[index]
            };
        });
        setFileImportMappingObject((prev) => {
            return Object.assign(Object.assign({}, prev), { mapping: fieldMappings });
        });
        setActiveStep((prev) => prev + 1);
    };
    const handleUpdateFileProperties = (values) => {
        setFileImportMappingObject((prev) => {
            let properties = {};
            Object.keys(values).forEach((propKey) => {
                var _a;
                return (properties[propKey] =
                    'value' in values[propKey]
                        ? (_a = values[propKey]) === null || _a === void 0 ? void 0 : _a.value
                        : values[propKey]);
            });
            return Object.assign(Object.assign({}, prev), { properties: properties });
        });
        if ('includesHeader' in values && (values === null || values === void 0 ? void 0 : values.includesHeader.value) === false) {
            setShowIndexNumbers(true);
        }
        handleFileUpload(values);
        setActiveStep((prev) => prev + 1);
    };
    const getUdpFieldOptionLabel = (option) => {
        if (!option.dataType.endsWith('?') &&
            !option.isPrimaryKey &&
            !option.udpType) {
            return `${option.name.replace(/([A-Z])/g, ' $1').trim()}*`; //required field
        }
        return `${option.name} - ${option.dataType}`;
    };
    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);
    };
    const formattedFileTypeProperties = useMemo(() => {
        if (selectedFileType) {
            return JSON.parse(selectedFileType === null || selectedFileType === void 0 ? void 0 : selectedFileType.properties);
        }
    }, [selectedFileType]);
    return (React.createElement(React.Fragment, null, React.createElement(UdpCard, { width: "100%" }, React.createElement("div", { style: { marginBottom: 20 } }, React.createElement(AmbientStepper, { activeStep: activeStep, steps: ['File', 'Domain', 'Field Mappings', 'Review'], orientation: "vertical" })), activeStep === 0 && (React.createElement(React.Fragment, null, React.createElement(UdpDropdown, { name: 'fileImportType', label: "File Type", onChange: (e) => setSelectedFileType(e.target.value), options: allowedFileTypesData || [], optionLabel: "name", optionValue: "id", value: selectedFileType, required: true }), selectedFileType && (React.createElement("div", { style: { marginTop: 5 } }, React.createElement(UdpFileInput, { value: fileItems, onChange: handleAddFileToUpload, accept: ".csv,.txt,.xlsx,.json", maxFiles: 1 }))), React.createElement(Form, { id: "fileProperties", onSubmit: handleUpdateFileProperties }, formattedFileTypeProperties === null || formattedFileTypeProperties === void 0 ? void 0 : formattedFileTypeProperties.map((property) => (property === null || property === void 0 ? void 0 : property.options) ? (React.createElement(Field, { key: property.propertyName, component: UdpDropdown, multiple: false, name: property.propertyName, label: property.label, options: property.options, optionLabel: "name", optionValue: "value", required: property === null || property === void 0 ? void 0 : property.required })) : (React.createElement(Field, { key: property.propertyName, component: UdpTextInput, name: property.propertyName, label: property.label, required: property === null || property === void 0 ? void 0 : property.required }))), React.createElement(UdpButton, { appearance: "secondary", type: "submit", form: "fileProperties", disabled: !fileObject }, "Nex")))), activeStep === 1 && (React.createElement(React.Fragment, null, React.createElement(UdpAutocomplete, { name: 'domain', label: "Domain", onChange: (e) => setSelectedDomain(e.target.value), options: filterCatalogObjectList, optionLabel: getNameFormattedOptionLabel, optionValue: "id", value: selectedDomain, required: true }), React.createElement("div", { style: { float: 'right', display: 'flex', gap: 8, marginTop: 8 } }, React.createElement(UdpButton, { onClick: () => setActiveStep((prev) => prev - 1), disabled: activeStep === 0 }, "Pre"), React.createElement(UdpButton, { appearance: "secondary", onClick: () => setActiveStep((prev) => prev + 1), disabled: !selectedDomain }, "Nex")))), activeStep === 2 && (React.createElement(React.Fragment, null, React.createElement("div", { style: {
            display: 'flex',
            flexDirection: 'row',
            justifyContent: 'space-between',
            paddingTop: 20
        } }, React.createElement(UdpText, { variant: "caption1Strong" }, showIndexNumbers ? "Column index's" : 'File Headers'), React.createElement(UdpText, { variant: "caption1Strong" }, "UDP Fields")), React.createElement(UdpDivider, { style: { margin: '5px 0px' } }), React.createElement(Form, { id: "fieldMappings", onSubmit: handleUpdateFieldMapping }, importHeaderData === null || importHeaderData === void 0 ? void 0 : importHeaderData.map((field, index) => (React.createElement("div", { key: index }, React.createElement("div", { style: {
            display: 'flex',
            flexDirection: 'row',
            alignItems: 'center',
            gap: 10
        } }, React.createElement(UdpText, { style: { width: '40%' } }, showIndexNumbers ? 'index ' + index : field), React.createElement(UdpIcon, { style: { width: '10%' }, name: "arrow-right" }), React.createElement("div", { style: { flex: 2 } }, React.createElement(Field, { component: UdpDropdown, multiple: false, name: `udpFieldMapping${index}`, options: selectedDomain === null || selectedDomain === void 0 ? void 0 : selectedDomain.objectFieldInfo, optionLabel: getUdpFieldOptionLabel, optionValue: "businessObjectKey", includeErrorPadding: false, clearable: true }))), React.createElement(UdpDivider, { style: { margin: '5px 0px' } })))), React.createElement("div", { style: { paddingTop: 20, textAlign: 'right', color: 'red' } }, errorText), React.createElement("div", { style: {
            display: 'flex',
            justifyContent: 'flex-start',
            gap: 8,
            paddingTop: 16
        } }, React.createElement(UdpButton, { onClick: () => setActiveStep((prev) => prev - 1), disabled: activeStep === 0 }, "Pre"), React.createElement(UdpButton, { appearance: "secondary", type: "submit", form: "fieldMappings" }, "Nex"))))), activeStep === 3 && (React.createElement(Form, { id: "createMapping", onSubmit: handleCreateNewFieldMapping }, React.createElement(Field, { component: UdpTextInput, name: `name`, label: "Mapping Name" }), React.createElement("div", { style: {
            display: 'flex',
            justifyContent: 'flex-start',
            gap: 8,
            paddingTop: 16
        } }, React.createElement(UdpButton, { onClick: () => setActiveStep((prev) => prev - 1), disabled: activeStep === 0 }, "Pre"), React.createElement(UdpButton, { appearance: "primary", type: "submit", form: "createMapping" }, "Create Mappin"))))), (fileImportMappingObject === null || fileImportMappingObject === void 0 ? void 0 : fileImportMappingObject.mapping) && React.createElement("div", { style: { marginTop: 10 } }, React.createElement(FileImportConfigCard, { fileMappingRecord: {
            mapping: fileImportMappingObject === null || fileImportMappingObject === void 0 ? void 0 : fileImportMappingObject.mapping,
            properties: fileImportMappingObject === null || fileImportMappingObject === void 0 ? void 0 : fileImportMappingObject.properties
        }, domain: selectedDomain === null || selectedDomain === void 0 ? void 0 : selectedDomain.name.replace(/([A-Z])/g, ' $1').trim() }))));
};
export default FileImportMappingWizard;
//# sourceMappingURL=FileImportMappingWizard.js.map