import React, { forwardRef, useCallback, useImperativeHandle, useMemo, useRef } from 'react';
import { arrayMutators, Field, Form } from '../../../../utilities/form';
import { FormControlLabel, makeStyles, Switch } from '@material-ui/core';
import { useTranslation } from 'react-i18next';
import { AmbientAutoComplete, FluentTextField } from '../../../../UI/inputs/textField';
import { FluentButton } from '../../../../UI/inputs/buttons';
import { FieldArray } from 'react-final-form-arrays';
import { StatusCircleErrorXIcon } from '@fluentui/react-icons';
import { EMPTY_GUID } from '../../../../enums';
import { LayoutUnit } from '../../../../layout';
import { DOMAIN_VALUE_OPERATORS } from '../../../utilities/transactionConstants';
const useStyles = makeStyles((theme) => ({
    domainFields: {
        display: 'flex',
        flexDirection: 'row',
        alignItems: 'flex-end',
        justifyContent: 'flex-start',
        '& > *': {
            marginRight: theme.spacing(2)
        }
    },
    domainValueField: {
        minWidth: '200px'
    },
    addRemoveButtons: {
        display: 'flex',
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'flex-start',
        margin: `${theme.spacing(2)}px  0  0 ${-theme.spacing(2)}px`,
        '& > *': {
            margin: `0 ${theme.spacing(2)}px`
        }
    },
    removeIcon: {
        fontSize: theme.spacing(3.5),
        marginTop: theme.spacing(1)
    },
    noRemoveIcon: {
        marginLeft: theme.spacing(3.5)
    }
}));
const noStatus = {
    name: 'No Status',
    transactionTypeStatusId: EMPTY_GUID
};
const UdpTransactionTypeConfigurationForm = (props, ref) => {
    const { onSubmit, initialData, transactionRuleTypes, catalogObjectProperties, transactionTypeStatusOptions, roles } = props;
    const handleSubmitRef = useRef();
    const { t } = useTranslation();
    const classes = useStyles();
    const ttstatusesWithNostatusOption = useMemo(() => {
        let ttstatuses;
        if (!transactionTypeStatusOptions)
            return;
        ttstatuses = [...transactionTypeStatusOptions, noStatus];
        return ttstatuses;
    }, [transactionTypeStatusOptions]);
    const formInitialValues = useMemo(() => {
        var _a, _b;
        let formattedData;
        if (!initialData)
            return;
        formattedData = Object.assign(Object.assign({}, initialData), { transactionRuleType: transactionRuleTypes === null || transactionRuleTypes === void 0 ? void 0 : transactionRuleTypes.find((trt) => (trt === null || trt === void 0 ? void 0 : trt.transactionRuleTypeId) === (initialData === null || initialData === void 0 ? void 0 : initialData.transactionRuleTypeId)), currentStatus: ttstatusesWithNostatusOption === null || ttstatusesWithNostatusOption === void 0 ? void 0 : ttstatusesWithNostatusOption.find((tts) => {
                var _a;
                return (tts === null || tts === void 0 ? void 0 : tts.transactionTypeStatusId) ===
                    ((_a = initialData === null || initialData === void 0 ? void 0 : initialData.configuration) === null || _a === void 0 ? void 0 : _a.currentStatusId);
            }), tenantUserRoles: roles === null || roles === void 0 ? void 0 : roles.filter((role) => {
                var _a, _b;
                return (_b = (_a = initialData === null || initialData === void 0 ? void 0 : initialData.configuration) === null || _a === void 0 ? void 0 : _a.tenantUserRoleIds) === null || _b === void 0 ? void 0 : _b.includes(role === null || role === void 0 ? void 0 : role.roleId);
            }), currentDomainValue: ((_a = initialData === null || initialData === void 0 ? void 0 : initialData.configuration) === null || _a === void 0 ? void 0 : _a.currentDomainValue)
                ? Object.entries((_b = initialData === null || initialData === void 0 ? void 0 : initialData.configuration) === null || _b === void 0 ? void 0 : _b.currentDomainValue).map(([fieldKey, fieldConfig]) => {
                    const normalizedFieldConfig = fieldConfig && typeof fieldConfig === 'object'
                        ? fieldConfig
                        : { value: fieldConfig };
                    const operatorOption = DOMAIN_VALUE_OPERATORS.find((option) => option.value === (normalizedFieldConfig === null || normalizedFieldConfig === void 0 ? void 0 : normalizedFieldConfig.operator)) || null;
                    return [
                        fieldKey,
                        Object.assign(Object.assign({}, normalizedFieldConfig), { operator: operatorOption })
                    ];
                })
                : [[]] });
        return formattedData;
    }, [initialData, transactionRuleTypes, roles, ttstatusesWithNostatusOption]);
    useImperativeHandle(ref, () => ({
        submit: () => {
            // eslint-disable-next-line no-unused-expressions
            handleSubmitRef === null || handleSubmitRef === void 0 ? void 0 : handleSubmitRef.current();
        }
    }));
    const handleSubmit = useCallback((formData) => {
        onSubmit(formData, initialData);
    }, [initialData, onSubmit]);
    return (React.createElement(Form, { onSubmit: handleSubmit, mutators: Object.assign({}, arrayMutators), initialValues: Object.assign({}, formInitialValues), render: ({ handleSubmit, form }) => {
            var _a;
            var _b;
            handleSubmitRef.current = handleSubmit;
            const push = (_b = (_a = form === null || form === void 0 ? void 0 : form.mutators) === null || _a === void 0 ? void 0 : _a.push) !== null && _b !== void 0 ? _b : (() => { });
            return (React.createElement(React.Fragment, null, React.createElement(Field, { component: FluentTextField, label: t('Name'), id: "name", name: "name", fullWidth: true, variant: "outlined", margin: "normal", size: "small" }), React.createElement(Field, { component: AmbientAutoComplete, label: t('Transaction Rule Type'), id: "transactionRuleType", name: "transactionRuleType", variant: "outlined", isMultiple: false, disableCloseOnSelect: false, options: transactionRuleTypes || [], getOptionLabelFunction: (option) => option.name, valueForChange: (value) => {
                    return value;
                }, required: true }), React.createElement(Field, { component: FluentTextField, label: t('Order'), id: "order", name: "order", fullWidth: true, variant: "outlined", margin: "normal", size: "small", type: "number", required: true }), React.createElement(LayoutUnit, { unit: "nudge" }), React.createElement(FormControlLabel, { control: React.createElement(Field, { component: Switch, id: "enabled", name: "enabled", type: "checkbox", defaultValue: true }), label: t('Enabled') }), React.createElement(Field, { component: AmbientAutoComplete, label: t('Current Status'), id: "currentStatus", name: "currentStatus", variant: "outlined", isMultiple: false, disableCloseOnSelect: false, options: ttstatusesWithNostatusOption || [], getOptionLabelFunction: (option) => option.name }), React.createElement(Field, { component: AmbientAutoComplete, label: t('Allowed Roles'), id: "tenantUserRoles", name: "tenantUserRoles", variant: "outlined", isMultiple: true, disableCloseOnSelect: true, groupBy: (option) => option.productName, options: roles || [], getOptionLabelFunction: (option) => option.name }), React.createElement(React.Fragment, null, React.createElement("div", { className: classes.addRemoveButtons }, React.createElement(FluentButton, { variant: "contained", color: "primary", onClick: () => push('currentDomainValue', undefined) }, t('Add a Domain Field'))), React.createElement(FieldArray, { name: "currentDomainValue" }, ({ fields }) => fields.map((name, index) => (React.createElement("div", { key: `${name}${index}`, className: classes.domainFields }, React.createElement(Field, { component: AmbientAutoComplete, label: index === 0 && t('Field'), name: `${name}[0]`, variant: "outlined", isMultiple: false, disableCloseOnSelect: false, options: catalogObjectProperties || [], getOptionLabelFunction: (option) => option, onChange: () => { } }), React.createElement(Field, { component: AmbientAutoComplete, label: index === 0 && t('Operator'), name: `${name}[1].operator`, variant: "outlined", isMultiple: false, disableCloseOnSelect: false, options: DOMAIN_VALUE_OPERATORS || [], getOptionLabelFunction: (option) => option.name, onChange: () => { } }), React.createElement(Field, { component: FluentTextField, label: index === 0 && t('Value'), name: `${name}[1].value`, fullWidth: true, variant: "outlined", margin: "normal", size: "small", onChange: () => { }, className: classes.domainValueField }), React.createElement("span", { onClick: () => fields.remove(index), style: { cursor: 'pointer' }, className: classes.removeIcon }, React.createElement(StatusCircleErrorXIcon, null)))))))));
        } }));
};
export default forwardRef(UdpTransactionTypeConfigurationForm);
//# sourceMappingURL=UdpTransactionTypeConfigurationForm.js.map