"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConfigMapForm = void 0;
const tslib_1 = require("tslib");
const react_1 = tslib_1.__importDefault(require("react"));
const fuse_js_1 = tslib_1.__importDefault(require("fuse.js"));
const formik_1 = require("formik");
const react_core_1 = require("@patternfly/react-core");
const common_1 = require("../../../../common");
const ClusterDeploymentWizardContext_1 = require("../ClusterDeploymentWizardContext");
const ValidationSection_1 = require("../components/ValidationSection");
const ConfigMapDetail_1 = require("./ConfigMapDetail");
const hooks_1 = require("../../../hooks");
const NO_RESULTS = 'no_results';
const ConfigMapForm = ({ namespace }) => {
    const { t } = (0, common_1.useTranslation)();
    const { syncError } = react_1.default.useContext(ClusterDeploymentWizardContext_1.ClusterDeploymentWizardContext);
    const { alerts, addAlert, clearAlerts } = (0, common_1.useAlerts)();
    const [isSubmitting, setSubmitting] = react_1.default.useState(false);
    const { activeStep, goToPrevStep, goToNextStep, close } = (0, react_core_1.useWizardContext)();
    const { values, errors, isValid, setFieldValue, submitForm } = (0, formik_1.useFormikContext)();
    const [filter, setFilter] = react_1.default.useState('');
    const [configMaps, setConfigMaps] = react_1.default.useState([]);
    const [data, loaded, isError] = (0, hooks_1.useConfigMaps)({
        namespace,
        isList: true,
    });
    react_1.default.useEffect(() => {
        if (data && loaded && !isError) {
            setConfigMaps(data.map((configMap) => {
                var _a, _b;
                return ({
                    value: {
                        name: (_a = configMap.metadata) === null || _a === void 0 ? void 0 : _a.name,
                        valid: true,
                        manifestNames: Object.keys(configMap.data || {}),
                    },
                    children: (_b = configMap.metadata) === null || _b === void 0 ? void 0 : _b.name,
                });
            }));
        }
    }, [data, isError, loaded]);
    react_1.default.useEffect(() => {
        if (loaded && !isError) {
            const newConfigMaps = values.configMaps.map((configMap) => {
                const map = data.find((item) => { var _a; return ((_a = item.metadata) === null || _a === void 0 ? void 0 : _a.name) === configMap.name; });
                if (map) {
                    return Object.assign(Object.assign({}, configMap), { valid: true, manifestNames: Object.keys(map.data || {}) });
                }
                return Object.assign(Object.assign({}, configMap), { valid: false, manifestNames: [] });
            });
            setFieldValue('configMaps', newConfigMaps);
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [data, isError, loaded, setFieldValue]);
    const placeholder = react_1.default.useMemo(() => {
        if (values.configMaps.length > 0) {
            return `${values.configMaps.length} config map${values.configMaps.length !== 1 ? 's' : ''} selected`;
        }
        return 'No config map selected';
    }, [values.configMaps]);
    const fuse = react_1.default.useMemo(() => new fuse_js_1.default(Object.values(configMaps), {
        includeScore: true,
        ignoreLocation: true,
        threshold: 0.3,
        keys: ['value.name'],
    }), [configMaps]);
    const selectOptions = react_1.default.useMemo(() => {
        if (filter) {
            const newSelectOptions = fuse
                .search(filter)
                .sort((a, b) => (a.score || 0) - (b.score || 0))
                .map(({ item }) => item);
            if (!newSelectOptions.length) {
                return [
                    {
                        isAriaDisabled: true,
                        children: t('ai:No results found for {{filter}}', { filter }),
                        value: NO_RESULTS,
                        hasCheckbox: false,
                    },
                ];
            }
            return newSelectOptions;
        }
        return configMaps;
    }, [filter, configMaps, fuse, t]);
    const submittingText = react_1.default.useMemo(() => {
        if (isSubmitting) {
            return t('ai:Saving changes...');
        }
        return undefined;
    }, [isSubmitting, t]);
    const onNext = react_1.default.useCallback(() => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
        try {
            clearAlerts();
            setSubmitting(true);
            yield submitForm();
            yield goToNextStep();
        }
        catch (error) {
            addAlert({
                title: t('ai:Failed to save ClusterDeployment'),
                message: error instanceof Error ? error.message : undefined,
            });
        }
        finally {
            setSubmitting(false);
        }
    }), [addAlert, clearAlerts, goToNextStep, submitForm, t]);
    const footer = react_1.default.useMemo(() => (react_1.default.createElement(react_core_1.WizardFooter, { activeStep: activeStep, onNext: onNext, nextButtonProps: { isLoading: !!submittingText }, nextButtonText: submittingText || t('ai:Next'), isNextDisabled: !isValid || !loaded, onBack: goToPrevStep, onClose: close })), [activeStep, onNext, submittingText, t, isValid, loaded, goToPrevStep, close]);
    (0, react_core_1.useWizardFooter)(footer);
    const errorAlert = typeof errors.configMaps === 'string' ? (react_1.default.createElement(react_core_1.GridItem, null,
        react_1.default.createElement(react_core_1.Alert, { variant: react_core_1.AlertVariant.danger, title: errors.configMaps, isInline: true }))) : (react_1.default.createElement(react_core_1.GridItem, null,
        react_1.default.createElement(react_core_1.Alert, { variant: react_core_1.AlertVariant.danger, title: t('ai:Some config map items are invalid'), isInline: true })));
    return (react_1.default.createElement(react_core_1.Grid, { hasGutter: true },
        react_1.default.createElement(react_core_1.GridItem, null,
            react_1.default.createElement(react_core_1.Stack, { hasGutter: true },
                react_1.default.createElement(react_core_1.StackItem, null,
                    react_1.default.createElement(common_1.SelectFieldWithSearch, { name: 'configMaps', label: t('ai:Config maps'), isMultiSelect: true, isRequired: true, isLoading: !loaded, selectOptions: selectOptions, filterValue: filter, setFilterValue: setFilter, placeholder: placeholder, helperText: t('ai:Select config maps from the list or use the type ahead to narrow down the list.') })),
                react_1.default.createElement(react_core_1.StackItem, null,
                    react_1.default.createElement(react_core_1.Grid, { hasGutter: true },
                        react_1.default.createElement(formik_1.FieldArray, { name: "configMaps" }, ({ remove }) => values.configMaps.map((configMap, index) => (react_1.default.createElement(ConfigMapDetail_1.ConfigMapDetail, { index: index, key: configMap.name, configMapName: configMap.name, configMap: data.find((item) => { var _a; return ((_a = item.metadata) === null || _a === void 0 ? void 0 : _a.name) === configMap.name; }), onRemove: () => remove(index), isLoading: !loaded })))))))),
        !isValid && errorAlert,
        !!isError && (react_1.default.createElement(react_core_1.GridItem, null,
            react_1.default.createElement(react_core_1.Alert, { variant: react_core_1.AlertVariant.danger, title: t('ai:An error occurred while fetching config maps'), isInline: true }))),
        !!alerts.length && (react_1.default.createElement(react_core_1.GridItem, null,
            react_1.default.createElement(common_1.Alerts, null))),
        syncError && (react_1.default.createElement(react_core_1.GridItem, null,
            react_1.default.createElement(ValidationSection_1.ValidationSection, { currentStepId: 'custom-manifests', hosts: [] },
                react_1.default.createElement(react_core_1.Alert, { variant: react_core_1.AlertVariant.danger, title: t('ai:An error occurred'), isInline: true }, syncError))))));
};
exports.ConfigMapForm = ConfigMapForm;
//# sourceMappingURL=ConfigMapForm.js.map