import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// (C) 2020-2026 GoodData Corporation
import { useCallback, useState } from "react";
import cx from "classnames";
import { useIntl } from "react-intl";
import { idRef, insightTitle, insightVisualizationType, isInsight, } from "@gooddata/sdk-model";
import { Button, FullScreenOverlay, Overlay, OverlayController, OverlayControllerProvider, RichText, UiIcon, UiTooltip, isNotDocumentFocused, useIdPrefixed, useMediaQuery, } from "@gooddata/sdk-ui-kit";
import { DOWNLOADER_ID } from "../../../../../_staging/fileUtils/downloadFile.js";
import { useDashboardSelector } from "../../../../../model/react/DashboardStoreProvider.js";
import { useWidgetExecutionsHandler } from "../../../../../model/react/useWidgetExecutionsHandler.js";
import { selectEnableRichTextDynamicReferences, selectSeparators, } from "../../../../../model/store/config/configSelectors.js";
import { selectExecutionTimestamp } from "../../../../../model/store/ui/uiSelectors.js";
import { DASHBOARD_HEADER_OVERLAYS_Z_INDEX } from "../../../../constants/zIndex.js";
import { useDashboardComponentsContext } from "../../../../dashboardContexts/DashboardComponentsContext.js";
import { WithDrillSelect } from "../../../../drill/DrillSelect/WithDrillSelect.js";
import { IntlWrapper } from "../../../../localization/IntlWrapper.js";
import { ThemedLoadingEqualizer } from "../../../../presentationComponents/ThemedLoadingEqualizer.js";
import { useInsightExport } from "../../../common/useInsightExport.js";
import { useShowAsTable } from "../../../showAsTableButton/useShowAsTable.js";
import { supportsShowAsTable } from "../../insightToTable.js";
import { DrillDialog } from "./DrillDialog.js";
import { DrillDialogInsight } from "./DrillDialogInsight.js";
import { getTitleWithBreadcrumbs } from "./getTitleWithBreadcrumbs.js";
// Header z-index start at  6000 so we need force all overlays z-indexes start at 6000 to be above header
const overlayController = OverlayController.getInstance(DASHBOARD_HEADER_OVERLAYS_Z_INDEX);
const overlayIgnoredClasses = [
    ".s-sort-direction-arrow",
    ".gd-export-dialog",
    ".options-menu-export-xlsx",
    ".options-menu-export-csv",
    `#${DOWNLOADER_ID}`,
];
const defaultDescriptionConfig = {
    source: "insight",
    includeMetrics: false,
    visible: true,
};
const getInsightWidgetDescription = (descriptionConfig, widget, insight) => {
    // We will handler description configuration only for insight widget that is
    // same as insight in dialog
    if (isInsight(widget) && widget.insight.identifier === insight?.identifier) {
        if (!descriptionConfig.visible) {
            return undefined;
        }
        const useInsightDescription = descriptionConfig.source === "insight";
        return useInsightDescription ? insight?.summary : widget?.description;
    }
    // If widget is not insight or insight is not same as insight in dialog, we will use insight summary as default
    return insight?.summary;
};
const DRILL_MODAL_EXECUTION_PSEUDO_REF = idRef("@@GDC_DRILL_MODAL");
export function InsightDrillDialog(props) {
    const { widget, locale, breadcrumbs, insight, enableDrillDescription, drillStep, returnFocusToInsight, onClose, onBackButtonClick, onDrillDown, onDrillStart, } = props;
    const isMobileDevice = useMediaQuery("mobileDevice");
    const [isLoading, setIsLoading] = useState(false);
    const executionsHandler = useWidgetExecutionsHandler(DRILL_MODAL_EXECUTION_PSEUDO_REF);
    const { ErrorComponent, LoadingComponent } = useDashboardComponentsContext({
        /**
         * There is a need to use Loading spinner instead of "Running three dots" loader while drill is loading.
         * If no custom loading component is provided, LoadingComponent defaults to Loading spinner.
         */
        LoadingComponent: ThemedLoadingEqualizer,
    });
    const handleLoadingChanged = useCallback(({ isLoading }) => {
        setIsLoading(isLoading);
        executionsHandler.onLoadingChanged.call(null, { isLoading });
    }, [executionsHandler.onLoadingChanged]);
    const [widgetFilters, setWidgetFilters] = useState(undefined);
    const handleFiltersReady = useCallback((filters) => {
        setWidgetFilters(filters);
    }, []);
    const baseInsightTitle = insightTitle(insight);
    const { exportCSVEnabled, exportXLSXEnabled, exportCSVRawEnabled, exportPdfTabularEnabled, isExportRawVisible, isExporting, isExportPdfTabularVisible, onExportRawCSV, onExportCSV, onExportXLSX, onExportPdfTabular, } = useInsightExport({
        title: getTitleWithBreadcrumbs(baseInsightTitle, breadcrumbs),
        widgetRef: DRILL_MODAL_EXECUTION_PSEUDO_REF,
        insight,
        widget,
        enableNewTabularExport: false,
    });
    const dialogId = useIdPrefixed(`drillDialog-${breadcrumbs.length}`);
    const descriptionId = useIdPrefixed(`description-${breadcrumbs.length}`);
    const OverlayComponent = isMobileDevice ? FullScreenOverlay : Overlay;
    const [isOpen, setIsOpen] = useState(false);
    const descriptionConfig = widget.configuration?.description ?? defaultDescriptionConfig;
    const description = getInsightWidgetDescription(descriptionConfig, widget, insight.insight);
    // Get original widget state but don't use its toggleWidgetAsTable to avoid affecting original widget
    const originalWidgetShowAsTableState = useShowAsTable(widget).isWidgetAsTable;
    // Use local state for drill dialog to isolate from original widget
    const [drillDialogIsAsTable, setDrillDialogIsAsTable] = useState(originalWidgetShowAsTableState);
    // Create isolated toggle function that only affects local state
    const toggleWidgetAsTable = useCallback(() => {
        setDrillDialogIsAsTable((prev) => !prev);
    }, []);
    const onCloseDialog = () => {
        onClose();
    };
    const isShowAsTableVisible = supportsShowAsTable(insightVisualizationType(insight));
    return (_jsx(OverlayControllerProvider, { overlayController: overlayController, children: _jsx(OverlayComponent, { className: "gd-drill-modal-overlay", isModal: true, closeOnEscape: true, closeOnOutsideClick: true, ignoreClicksOnByClass: overlayIgnoredClasses, onClose: onCloseDialog, positionType: "fixed", children: _jsx(IntlWrapper, { locale: locale, children: _jsx(DrillDialog, { insight: insight, widget: widget, insightTitle: baseInsightTitle, isBackButtonVisible: breadcrumbs.length > 1, onBackButtonClick: onBackButtonClick, onCloseDialog: onCloseDialog, breadcrumbs: breadcrumbs, exportAvailable: exportXLSXEnabled || exportCSVEnabled, exportXLSXEnabled: exportXLSXEnabled, exportCSVEnabled: exportCSVEnabled, exportCSVRawEnabled: exportCSVRawEnabled, exportPDFEnabled: exportPdfTabularEnabled, exportPDFVisible: isExportPdfTabularVisible, enableDrillDescription: enableDrillDescription, onExportXLSX: onExportXLSX, onExportCSV: onExportCSV, onExportCSVRaw: onExportRawCSV, onExportPDF: onExportPdfTabular, isLoading: isLoading, isExporting: isExporting, isExportRawVisible: isExportRawVisible, isShowAsTableVisible: isShowAsTableVisible, isWidgetAsTable: drillDialogIsAsTable, onShowAsTable: toggleWidgetAsTable, focusCheckFn: isNotDocumentFocused, accessibilityConfig: {
                        dialogId,
                    }, children: _jsx(WithDrillSelect, { widgetRef: widget.ref, insight: props.insight, returnFocusToInsight: returnFocusToInsight, onDrillStart: onDrillStart, onDrillDownSuccess: onDrillDown, children: ({ onDrill }) => {
                            return description && enableDrillDescription ? (_jsxs("div", { className: "drill-dialog-insight-container", children: [
                                    _jsxs("div", { className: "drill-dialog-insight-container-insight", children: [
                                            _jsx(InsightDrillDialogDescriptionButton, { isOpen: isOpen, isMobileDevice: isMobileDevice, setIsOpen: setIsOpen, descriptionId: descriptionId }), _jsx(DrillDialogInsight, { ...props, onDrill: onDrill, onLoadingChanged: handleLoadingChanged, onError: executionsHandler.onError, onWidgetFiltersReady: handleFiltersReady, pushData: executionsHandler.onPushData, ErrorComponent: ErrorComponent, LoadingComponent: LoadingComponent, drillStep: drillStep, isWidgetAsTable: drillDialogIsAsTable })
                                        ] }), _jsx(InsightDrillDialogDescriptionContent, { id: descriptionId, isOpen: isOpen, isMobileDevice: isMobileDevice, description: description, widgetFilters: widgetFilters, LoadingComponent: LoadingComponent })
                                ] })) : (_jsx(DrillDialogInsight, { ...props, onDrill: onDrill, onLoadingChanged: handleLoadingChanged, onError: executionsHandler.onError, pushData: executionsHandler.onPushData, ErrorComponent: ErrorComponent, LoadingComponent: LoadingComponent, drillStep: drillStep, isWidgetAsTable: drillDialogIsAsTable }));
                        } }) }) }) }) }));
}
function InsightDrillDialogDescriptionButton({ isOpen, isMobileDevice, setIsOpen, descriptionId, }) {
    const { formatMessage } = useIntl();
    const accessibilityAriaLabel = formatMessage({ id: "widget.options.description" });
    return (_jsx(UiTooltip, { triggerBy: ["hover", "focus"], arrowPlacement: "left", offset: isOpen ? 15 : undefined, content: accessibilityAriaLabel, anchor: _jsx(Button, { className: cx("gd-button-primary gd-button-icon-only drill-dialog-insight-container-button", {
                "is-active": isOpen,
                "drill-dialog-insight-container-button--open": isOpen,
                "drill-dialog-insight-container-button--mobile": isMobileDevice,
            }), onClick: () => setIsOpen((open) => !open), accessibilityConfig: {
                ariaLabel: accessibilityAriaLabel,
                ariaDescribedBy: isOpen ? descriptionId : undefined,
                ariaControls: descriptionId,
                ariaExpanded: isOpen,
            }, value: _jsx(UiIcon, { type: "question", size: 18 }) }) }));
}
function InsightDrillDialogDescriptionContent({ id, isOpen, isMobileDevice, description, widgetFilters, LoadingComponent, }) {
    const isRichTextReferencesEnabled = useDashboardSelector(selectEnableRichTextDynamicReferences);
    const separators = useDashboardSelector(selectSeparators);
    const executionTimestamp = useDashboardSelector(selectExecutionTimestamp);
    return (_jsx("div", { id: id, className: cx("drill-dialog-insight-container-description", {
            "drill-dialog-insight-container-description--open": isOpen,
            "drill-dialog-insight-container-description--mobile": isMobileDevice,
        }), children: _jsx("div", { className: "drill-dialog-insight-container-description-content", children: _jsx(RichText, { value: description, execConfig: {
                    timestamp: executionTimestamp,
                }, renderMode: "view", referencesEnabled: isRichTextReferencesEnabled, filters: widgetFilters, separators: separators, LoadingComponent: LoadingComponent }) }) }));
}
//# sourceMappingURL=InsightDrillDialog.js.map