import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// (C) 2020-2026 GoodData Corporation
import { useCallback, useEffect, useMemo, useRef, useState, } from "react";
import { createSelector } from "@reduxjs/toolkit";
import { insightSetFilters } from "@gooddata/sdk-model";
import { useBackendStrict, useWorkspaceStrict, } from "@gooddata/sdk-ui";
import { useDashboardSelector } from "../../../../../model/react/DashboardStoreProvider.js";
import { useWidgetFilters } from "../../../../../model/react/useWidgetFilters.js";
import { selectCatalogAttributes } from "../../../../../model/store/catalog/catalogSelectors.js";
import { selectAgGridToken, selectColorPalette, selectIsExport, selectLocale, selectMapboxToken, selectSeparators, selectSettings, } from "../../../../../model/store/config/configSelectors.js";
import { selectDrillableItems } from "../../../../../model/store/drill/drillSelectors.js";
import { selectPermissions } from "../../../../../model/store/permissions/permissionsSelectors.js";
import { selectPreloadedAttributesWithReferences } from "../../../../../model/store/tabs/filterContext/filterContextSelectors.js";
import { selectExecutionTimestamp } from "../../../../../model/store/ui/uiSelectors.js";
import { IntlWrapper } from "../../../../localization/IntlWrapper.js";
import { getGeoDefaultDisplayFormRefs } from "../../geoDefaultDisplayFormRefs.js";
import { InsightBody } from "../../InsightBody.js";
import { convertInsightToLayerTables, convertInsightToTableDefinition } from "../../insightToTable.js";
import { CustomError } from "../CustomError/CustomError.js";
import { useInsightPositionStyle } from "../useInsightPositionStyle.js";
import { useResolveDashboardInsightProperties } from "../useResolveDashboardInsightProperties.js";
import { useDrillDialogInsightDrills } from "./useDrillDialogInsightDrills.js";
import { useDrillDialogSyncInsightProperties } from "./useDrillDialogSyncInsightProperties.js";
import { useExcludedDrillDefinitionFilters } from "./useExcludedDrillDefinitionFilters.js";
const insightStyle = { width: "100%", height: "100%", position: "relative", flex: "1 1 auto" };
const selectCommonDashboardInsightProps = createSelector([selectLocale, selectSettings, selectColorPalette], (locale, settings, colorPalette) => ({
    locale,
    settings,
    colorPalette,
}));
const selectChartConfig = createSelector([selectMapboxToken, selectAgGridToken, selectSeparators, selectDrillableItems, selectIsExport], (mapboxToken, agGridToken, separators, drillableItems, isExport) => ({
    mapboxToken,
    agGridToken,
    separators,
    forceDisableDrillOnAxes: !drillableItems.length, // to keep in line with KD, enable axes drilling only if using explicit drills
    isExportMode: isExport,
}));
/**
 * @internal
 */
export function DrillDialogInsight({ insight, widget, backend, workspace, drillStep, onError, onDrill: onDrillFn, isWidgetAsTable, onExportReady, onLoadingChanged, onWidgetFiltersReady, pushData, ErrorComponent, LoadingComponent, }) {
    const visualizationContainerRef = useRef(null);
    // Context
    const effectiveBackend = useBackendStrict(backend);
    const effectiveWorkspace = useWorkspaceStrict(workspace);
    // State props
    const { locale, settings, colorPalette } = useDashboardSelector(selectCommonDashboardInsightProps);
    const permissions = useDashboardSelector(selectPermissions);
    const chartConfig = useDashboardSelector(selectChartConfig);
    const catalogAttributes = useDashboardSelector(selectCatalogAttributes);
    const preloadedAttributesWithReferences = useDashboardSelector(selectPreloadedAttributesWithReferences);
    // Loading and rendering
    const [isVisualizationLoading, setIsVisualizationLoading] = useState(false);
    const [visualizationError, setVisualizationError] = useState();
    const handleLoadingChanged = useCallback(({ isLoading }) => {
        setIsVisualizationLoading(isLoading);
        onLoadingChanged?.({ isLoading });
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);
    // Filtering
    const { result: availableFiltersForInsight, status: filtersStatus, error: filtersError, } = useWidgetFilters(widget, insight);
    const filtersForInsight = useExcludedDrillDefinitionFilters(availableFiltersForInsight, drillStep);
    const insightWithAddedFilters = useMemo(() => insightSetFilters(insight, filtersForInsight), [insight, filtersForInsight]);
    const insightWithAddedWidgetProperties = useResolveDashboardInsightProperties({
        insight: insightWithAddedFilters ?? insight,
        widget,
    });
    const { drillableItems, onDrill, onPushData } = useDrillDialogInsightDrills({
        widget,
        insight: insightWithAddedFilters ?? insight,
        onDrill: onDrillFn,
    });
    const { syncedInsight, handlePushData } = useDrillDialogSyncInsightProperties({
        insight: insightWithAddedWidgetProperties,
        drillStepInsightId: drillStep?.insight.insight.identifier,
        onPushData,
        pushData,
        isWidgetAsTable,
    });
    // Multi-layer geo → per-layer table tabs
    const layerTables = useMemo(() => isWidgetAsTable
        ? convertInsightToLayerTables(syncedInsight, {
            settings,
            catalogAttributes,
            preloadedAttributesWithReferences,
        })
        : undefined, [isWidgetAsTable, syncedInsight, settings, catalogAttributes, preloadedAttributesWithReferences]);
    // Convert insight to table format if needed for drill dialog
    const finalInsight = useMemo(() => {
        const defaultDisplayFormRefs = getGeoDefaultDisplayFormRefs(syncedInsight, settings, catalogAttributes, preloadedAttributesWithReferences);
        if (!isWidgetAsTable) {
            return syncedInsight;
        }
        return convertInsightToTableDefinition(syncedInsight, { settings, defaultDisplayFormRefs });
    }, [isWidgetAsTable, syncedInsight, settings, catalogAttributes, preloadedAttributesWithReferences]);
    // CSS
    const insightPositionStyle = useInsightPositionStyle();
    // Error handling
    const handleError = useCallback((error) => {
        setVisualizationError(error);
        onError?.(error);
    }, [onError]);
    const effectiveError = filtersError ?? visualizationError;
    const insightWrapperStyle = useMemo(() => {
        return isVisualizationLoading || effectiveError ? { height: 0 } : undefined;
    }, [isVisualizationLoading, effectiveError]);
    useEffect(() => {
        onWidgetFiltersReady?.(filtersForInsight);
    }, [filtersForInsight, onWidgetFiltersReady]);
    const executionTimestamp = useDashboardSelector(selectExecutionTimestamp);
    const execConfig = useMemo(() => ({ timestamp: executionTimestamp }), [executionTimestamp]);
    return (_jsx("div", { style: insightStyle, children: _jsx("div", { style: insightPositionStyle, children: _jsxs(IntlWrapper, { locale: locale, children: [filtersStatus === "running" || isVisualizationLoading ? _jsx(LoadingComponent, {}) : null, effectiveError ? (_jsx(CustomError, { error: effectiveError, 
                        // drill dialog does not measure its size but is always large enough to fit the full content
                        forceFullContent: true })) : null, filtersStatus === "success" ? (_jsx("div", { ref: visualizationContainerRef, className: "insight-view-visualization", style: insightWrapperStyle, children: _jsx(InsightBody, { widget: widget, insight: finalInsight, layerTables: layerTables && layerTables.length > 1 ? layerTables : undefined, backend: effectiveBackend, workspace: effectiveWorkspace, drillableItems: drillableItems, onDrill: onDrill, config: chartConfig, onLoadingChanged: handleLoadingChanged, locale: locale, settings: settings, permissions: permissions, colorPalette: colorPalette, onError: handleError, onExportReady: onExportReady, pushData: handlePushData, ErrorComponent: ErrorComponent, LoadingComponent: LoadingComponent, execConfig: execConfig, drillStep: drillStep }) })) : null] }) }) }));
}
//# sourceMappingURL=DrillDialogInsight.js.map