import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// (C) 2020-2026 GoodData Corporation
import { useCallback, useEffect, useState } from "react";
import { FormattedMessage, useIntl } from "react-intl";
import { objRefToString } from "@gooddata/sdk-model";
import { Bubble, BubbleHoverTrigger, ConfirmDialog, DialogListHeader, Dropdown, RecurrenceForm, SingleSelectListItem, UiButton, UiListbox, simpleRecurrenceTypeMappingFn, } from "@gooddata/sdk-ui-kit";
import { queryDateDatasetsForInsight, } from "../../model/queries/insights.js";
import { useDashboardSelector } from "../../model/react/DashboardStoreProvider.js";
import { useDashboardQueryProcessing } from "../../model/react/useDashboardQueryProcessing.js";
import { selectDateFormat, selectEnableAlertsEvaluationFrequencySetup, selectEnableDashboardSectionHeadersDateDataSet, selectIsWhiteLabeled, selectLocale, selectSettings, selectWeekStart, } from "../../model/store/config/configSelectors.js";
import { selectCrossFilteringEnabledAndSupported } from "../../model/store/topBar/topBarSelectors.js";
import { useDialogData } from "./useDialogData.js";
/**
 * @alpha
 */
export function DefaultDashboardSettingsDialog({ isVisible, onApply, onCancel /*, onError*/, }) {
    const intl = useIntl();
    const [cronValid, setCronValid] = useState(true);
    const { currentData, setCurrentData, isDirty } = useDialogData();
    const dateFormat = useDashboardSelector(selectDateFormat);
    const weekStart = useDashboardSelector(selectWeekStart);
    const locale = useDashboardSelector(selectLocale);
    const isCrossFilteringEnabledAndSupported = useDashboardSelector(selectCrossFilteringEnabledAndSupported);
    const enableAlertsEvaluationFrequencySetup = useDashboardSelector(selectEnableAlertsEvaluationFrequencySetup);
    const settings = useDashboardSelector(selectSettings);
    const isWhiteLabeled = useDashboardSelector(selectIsWhiteLabeled);
    const enableDashboardSectionHeadersDateDataSet = useDashboardSelector(selectEnableDashboardSectionHeadersDateDataSet);
    const { run: queryDateDatasets, result, status, } = useDashboardQueryProcessing({
        queryCreator: queryDateDatasetsForInsight,
    });
    useEffect(() => {
        if (isVisible && enableDashboardSectionHeadersDateDataSet) {
            queryDateDatasets();
        }
    }, [queryDateDatasets, isVisible, enableDashboardSectionHeadersDateDataSet]);
    const onApplyHandler = useCallback(() => {
        onApply(currentData);
    }, [onApply, currentData]);
    if (!isVisible) {
        return null;
    }
    return (_jsx(ConfirmDialog, { onCancel: onCancel, onSubmit: onApplyHandler, isPositive: true, className: "s-dialog s-settings_dashboard_dialog gd-dashboard-settings-dialog", headline: intl.formatMessage({ id: "settingsDashboardDialog.headline" }), cancelButtonText: intl.formatMessage({ id: "cancel" }), submitButtonText: intl.formatMessage({ id: "apply" }), isSubmitDisabled: !isDirty() || !cronValid, children: _jsxs("div", { className: "gd-dashboard-content-wrapper", children: [
                _jsxs("div", { className: "gd-dashboard-settings-dialog-section", children: [
                        _jsx(DialogListHeader, { title: intl.formatMessage({ id: "filters.configurationPanel.header" }), className: "gd-dashboard-settings-filters" }), isCrossFilteringEnabledAndSupported ? (_jsxs(_Fragment, { children: [
                                _jsx(ConfigurationOption, { label: intl.formatMessage({
                                        id: "filters.configurationPanel.crossFiltering.toggle",
                                    }), tooltip: intl.formatMessage({
                                        id: "filters.configurationPanel.crossFiltering.toggle.tooltip",
                                    }), isChecked: !currentData.disableCrossFiltering, onChange: (newValue) => {
                                        setCurrentData({
                                            ...currentData,
                                            disableCrossFiltering: newValue,
                                        });
                                    } }), _jsx(ConfigurationOption, { label: intl.formatMessage({
                                        id: "filters.configurationPanel.userFilterReset.toggle",
                                    }), tooltip: intl.formatMessage({
                                        id: "filters.configurationPanel.userFilterReset.toggle.tooltip",
                                    }), isChecked: !currentData.disableUserFilterReset, onChange: (newValue) => {
                                        setCurrentData({
                                            ...currentData,
                                            disableUserFilterReset: newValue,
                                        });
                                    } })
                            ] })) : null, _jsx(ConfigurationOption, { label: intl.formatMessage({
                                id: "filters.configurationPanel.filterViews.toggle",
                            }), tooltip: intl.formatMessage({ id: "filters.configurationPanel.filterViews.toggle.tooltip" }, {
                                p: (chunks) => _jsx("p", { children: chunks }),
                            }), isChecked: !currentData.disableFilterViews, onChange: (newValue) => {
                                setCurrentData({
                                    ...currentData,
                                    disableFilterViews: newValue,
                                });
                            } }), _jsx(ConfigurationOption, { label: intl.formatMessage({ id: "filters.configurationPanel.userFilterSave.toggle" }), tooltip: intl.formatMessage({
                                id: "filters.configurationPanel.userFilterSave.toggle.tooltip",
                            }), isChecked: !currentData.disableUserFilterSave, onChange: (newValue) => {
                                setCurrentData({
                                    ...currentData,
                                    disableUserFilterSave: newValue,
                                });
                            } }), enableDashboardSectionHeadersDateDataSet ? (_jsx(DateDatasetDropdown, { label: intl.formatMessage({
                                id: "settingsDashboardDialog.sectionHeaders.dateDataset",
                            }), tooltip: intl.formatMessage({
                                id: "settingsDashboardDialog.sectionHeaders.dateDataset.tooltip",
                            }), dateDatasets: result?.dateDatasetsOrdered ?? [], selectedDataSet: currentData.sectionHeadersDateDataSet, isLoading: status === "pending" || status === "running", onChange: (dateDataSet) => {
                                setCurrentData({
                                    ...currentData,
                                    sectionHeadersDateDataSet: dateDataSet,
                                });
                            } })) : null] }), enableAlertsEvaluationFrequencySetup ? (_jsxs("div", { className: "gd-dashboard-settings-dialog-section", children: [
                        _jsx(DialogListHeader, { title: intl.formatMessage({ id: "settingsDashboardDialog.section.alert" }), className: "gd-dashboard-settings-filters" }), _jsx(RecurrenceForm, { allowHourlyRecurrence: true, cronExpression: currentData.evaluationFrequency ?? "", placeholder: settings.alertDefault?.defaultCron, timezone: settings.alertDefault?.defaultTimezone, onChange: (e, _, valid) => {
                                setCronValid(valid);
                                setCurrentData({
                                    ...currentData,
                                    evaluationFrequency: e || undefined,
                                });
                            }, repeatLabel: intl.formatMessage({
                                id: "settingsDashboardDialog.section.alert.label",
                            }), showRepeatTypeDescription: true, showTimezoneInOccurrence: true, dateFormat: dateFormat, weekStart: weekStart, locale: locale, showInheritValue: true, isWhiteLabeled: isWhiteLabeled, customRecurrenceTypeMappingFn: simpleRecurrenceTypeMappingFn }), _jsx("div", { className: "gd-dashboard-settings-evaluation-note", children: currentData.evaluationFrequency === undefined ? (_jsx(FormattedMessage, { id: "settingsDashboardDialog.section.alert.inherit" })) : (_jsx(FormattedMessage, { id: "settingsDashboardDialog.section.alert.note", values: {
                                    strong: (chunks) => _jsx("strong", { children: chunks }),
                                } })) })
                    ] })) : null] }) }));
}
const BUBBLE_ALIGN_POINTS = [{ align: "bc tl" }];
function ConfigurationOption({ label, tooltip, isChecked, onChange }) {
    return (_jsx("div", { className: "configuration-category-item", children: _jsxs("label", { className: "input-checkbox-toggle", children: [
                _jsx("input", { type: "checkbox", checked: isChecked, onChange: (e) => {
                        onChange(!e.currentTarget.checked);
                    } }), _jsxs("span", { className: "input-label-text", children: [label, _jsxs(BubbleHoverTrigger, { showDelay: 0, hideDelay: 0, eventsOnBubble: true, className: "configuration-category-item-tooltip-icon", children: [
                                _jsx("span", { className: "gd-icon-circle-question gd-filter-configuration__help-icon" }), _jsx(Bubble, { alignPoints: BUBBLE_ALIGN_POINTS, children: _jsx("div", { className: "gd-filter-configuration__help-tooltip", children: tooltip }) })
                            ] })
                    ] })
            ] }) }));
}
function DateDatasetDropdown({ label, tooltip, dateDatasets, selectedDataSet, isLoading, onChange, }) {
    const intl = useIntl();
    const selectedDatasetTitle = isLoading
        ? intl.formatMessage({ id: "loading" })
        : selectedDataSet
            ? (dateDatasets.find((ds) => objRefToString(ds.dataSet.ref) === objRefToString(selectedDataSet))
                ?.dataSet.title ?? intl.formatMessage({ id: "dateDataset.notFound" }))
            : intl.formatMessage({ id: "dateDataset.autoSelect" });
    return (_jsxs("div", { className: "configuration-category-item", children: [
            _jsxs("span", { className: "input-label-text", children: [label, _jsxs(BubbleHoverTrigger, { showDelay: 0, hideDelay: 0, eventsOnBubble: true, className: "configuration-category-item-tooltip-icon", children: [
                            _jsx("span", { className: "gd-icon-circle-question gd-filter-configuration__help-icon" }), _jsx(Bubble, { alignPoints: BUBBLE_ALIGN_POINTS, children: _jsx("div", { className: "gd-filter-configuration__help-tooltip", children: tooltip }) })
                        ] })
                ] }), _jsx(Dropdown, { closeOnParentScroll: true, autofocusOnOpen: true, alignPoints: [{ align: "bl tl" }, { align: "tl bl" }], className: "gd-dashboard-settings-date-dataset-dropdown", renderButton: ({ isOpen, toggleDropdown }) => (_jsx(UiButton, { label: selectedDatasetTitle, onClick: toggleDropdown, isDisabled: isLoading, iconAfter: isOpen ? "navigateUp" : "navigateDown", size: "small" })), renderBody: ({ closeDropdown, ariaAttributes }) => {
                    const autoSelectItem = {
                        type: "interactive",
                        id: "__auto__",
                        stringTitle: intl.formatMessage({ id: "dateDataset.autoSelect" }),
                        data: undefined,
                    };
                    const datasetItems = dateDatasets.map((ds) => ({
                        type: "interactive",
                        id: objRefToString(ds.dataSet.ref),
                        stringTitle: ds.dataSet.title,
                        data: ds.dataSet.ref,
                    }));
                    const items = [autoSelectItem, ...datasetItems];
                    const selectedItemId = selectedDataSet ? objRefToString(selectedDataSet) : "__auto__";
                    return (_jsx(UiListbox, { maxWidth: 300, items: items, selectedItemId: selectedItemId, onSelect: (item) => {
                            onChange(item.data);
                            closeDropdown();
                        }, onClose: closeDropdown, ariaAttributes: ariaAttributes, InteractiveItemComponent: ({ item, isSelected, isFocused, onSelect }) => (_jsx(SingleSelectListItem, { className: "gd-dashboard-settings-dialog-date-dataset-dropdown-list-item", title: item.stringTitle, isSelected: isSelected, isFocused: isFocused, onClick: onSelect })) }));
                }, overlayPositionType: "sameAsTarget" })] }));
}
