import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { RequiredFieldsMappingField } from './RequiredFieldsMappingField';
import { ChromeBackMirroredIcon } from '@fluentui/react-icons';
import { FluentIcon } from '../../utilities/iconLibrary/FluentIcon';
import { Typography, makeStyles } from '@material-ui/core';
import { FluentButton } from '../../UI/inputs/buttons/FluentButton';
import { v4 as uuid } from 'uuid';
const useStyles = makeStyles((theme) => ({
    root: {},
    row: {
        display: 'flex',
        alignItems: 'center'
    },
    variableContainer: {
        width: '100%',
        display: 'flex',
        alignItems: 'flex-start'
    },
    icon: {
        marginTop: theme.spacing(5)
    },
    iconButton: {
        marginTop: theme.spacing(3.5)
    },
    iconContainer: {
        marginRight: theme.spacing(1)
    }
}));
export const RequiredFieldsMappingForm = (props) => {
    const { requiredFields = '', fieldMappings, properties, onSubmit = () => { }, optionLabelDisplayFunction, groupBy, propertyType = 'entity' } = props;
    const [fields, setFields] = useState([]);
    const classes = useStyles(props);
    const fieldOptions = useMemo(() => {
        const fieldsStr = requiredFields || '';
        if (!fieldsStr.trim()) {
            return [];
        }
        const options = [];
        const fields = fieldsStr.split(',');
        fields.forEach((field) => {
            options.push({ label: field.trim(), value: field.trim() });
        });
        return options;
    }, [requiredFields]);
    const handleRequiredFieldChange = useCallback((fieldId, value, key, merge = false) => {
        const updatedFields = [...fields];
        let matchingField = updatedFields.find((f) => f.id === fieldId);
        if (matchingField) {
            if (merge) {
                Object.keys(value).forEach((key) => {
                    matchingField[key] = value[key];
                });
            }
            else {
                matchingField[key] = value;
            }
        }
        setFields(updatedFields);
    }, [fields, setFields]);
    const propertyOptions = useMemo(() => {
        if (!properties) {
            return [];
        }
        // return properties.filter(
        //   (property) => property?.type !== 'array' && property?.type !== 'object'
        // );
        return properties;
    }, [properties]);
    const handleOnSubmit = useCallback(() => {
        // construct the mapping object from the values
        // the map would be {params.apple: appleValue}
        const fieldMappings = {};
        fields.forEach((field) => {
            var _a;
            fieldMappings[field.name] = {
                value: field.propertyValue
                    ? (_a = field.propertyValue) === null || _a === void 0 ? void 0 : _a.name
                    : field.strValue.trim(),
                type: field.propertyValue ? propertyType : 'custom'
            };
        });
        onSubmit(fieldMappings);
    }, [onSubmit, fields, propertyType]);
    useEffect(() => {
        if (!fieldOptions || !fieldMappings || !propertyOptions) {
            return;
        }
        const currentFields = [];
        fieldOptions.forEach((fo) => {
            const mappingValue = fieldMappings[fo.value];
            const currentField = {
                id: uuid(),
                strValue: (mappingValue === null || mappingValue === void 0 ? void 0 : mappingValue.type) === 'custom' ? mappingValue === null || mappingValue === void 0 ? void 0 : mappingValue.value : '',
                propertyValue: (mappingValue === null || mappingValue === void 0 ? void 0 : mappingValue.type) === propertyType
                    ? propertyOptions.find((po) => po.name === (mappingValue === null || mappingValue === void 0 ? void 0 : mappingValue.value))
                    : '',
                name: fo.value
            };
            currentFields.push(currentField);
        });
        setFields(currentFields);
    }, [fieldMappings, fieldOptions, propertyOptions, propertyType]);
    return (React.createElement("div", { className: classes.root }, fields.length > 0 &&
        fieldOptions.map((item) => {
            const matchingField = fields.find((field) => field.name === item.value);
            return (React.createElement("div", { className: classes.row }, React.createElement(RequiredFieldsMappingField, { requiredField: matchingField, onRequiredFieldChange: handleRequiredFieldChange, options: propertyOptions || [], optionLabelDisplayFunction: optionLabelDisplayFunction, groupBy: groupBy }), React.createElement("div", { className: classes.iconContainer }, React.createElement(FluentIcon, { component: ChromeBackMirroredIcon, size: 20, customSize: true })), React.createElement(Typography, { variant: "subtitle1", style: { textOverflow: 'ellipsis', overflow: 'hidden' } }, item.label)));
        }), React.createElement(FluentButton, { variant: "contained", color: "primary", fullWidth: true, onClick: handleOnSubmit }, ' ', "Save Mappin")));
};
//# sourceMappingURL=RequiredFieldsMappingForm.js.map