import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// (C) 2019-2026 GoodData Corporation
import { useMemo } from "react";
import cx from "classnames";
import { cloneDeep, compact, isEqual } from "lodash-es";
import { FormattedMessage, useIntl } from "react-intl";
import { invariant } from "ts-invariant";
import { areObjRefsEqual, isAttributeDescriptor, } from "@gooddata/sdk-model";
import { messages } from "@gooddata/sdk-ui";
import { simplifyText } from "@gooddata/util";
import { useDashboardSelector } from "../../../../model/react/DashboardStoreProvider.js";
import { selectCatalogDateDatasets } from "../../../../model/store/catalog/catalogSelectors.js";
import { selectEnableFilterControlInDrillingConfiguration } from "../../../../model/store/config/configSelectors.js";
import { selectDrillTargetsByWidgetRef } from "../../../../model/store/drillTargets/drillTargetsSelectors.js";
import { selectWidgetDrills } from "../../../../model/store/tabs/layout/layoutSelectors.js";
import { DRILL_TARGET_TYPE, isDrillDownToAttributeHierarchyConfig, isDrillToDashboardConfig, isDrillToInsightConfig, } from "../../../drill/types.js";
import { DrillFiltersTrigger } from "./DrillFilters/DrillFiltersTrigger.js";
import { useDrillFiltersCount } from "./DrillFilters/useDrillFiltersCount.js";
import { useDrillFiltersSubview } from "./DrillFilters/useDrillFiltersSubview.js";
import { DrillIntersectionIgnoredAttributes } from "./DrillIntersectionIgnoredAttributes.js";
import { DrillOriginItem } from "./DrillOriginItem.js";
import { DrillTargets } from "./DrillTargets/DrillTargets.js";
import { DrillTargetType } from "./DrillTargetType/DrillTargetType.js";
function disableDrillDownIfMeasure(enabledDrillTargetTypeItems, isMeasure, intl) {
    const drillTargetTypes = cloneDeep(enabledDrillTargetTypeItems);
    if (isMeasure) {
        const drillDownIndex = drillTargetTypes.findIndex((item) => item.id === DRILL_TARGET_TYPE.DRILL_DOWN);
        if (drillDownIndex >= 0) {
            const drillDownTarget = drillTargetTypes[drillDownIndex];
            drillDownTarget.disabled = true;
            drillDownTarget.disableTooltipMessage = intl.formatMessage(messages["drilldownTooltipDisabledMetric"]);
            drillTargetTypes.splice(drillDownIndex, 1, drillDownTarget);
        }
    }
    return drillTargetTypes;
}
export function DrillConfigItem({ item, enabledDrillTargetTypeItems, onIncompleteChange, onSetup, onDelete, }) {
    const intl = useIntl();
    const isDrillFiltersConfigEnabled = useDashboardSelector(selectEnableFilterControlInDrillingConfiguration);
    const { openDrillFilters } = useDrillFiltersSubview();
    const onDeleteClick = () => {
        onDelete(item);
    };
    const onDrillTargetTypeSelect = (target) => {
        onIncompleteChange({
            ...item,
            drillTargetType: target,
        });
    };
    const classNames = cx("s-drill-config-item", `s-drill-config-item-${simplifyText(item.title)}`, {
        "s-drill-config-item-incomplete": !item.complete,
    });
    const targetClassNames = cx("s-drill-config-target", "drill-config-target", {
        "drill-config-target-with-warning": !!item.warning,
    });
    const { count: selectedFiltersCount, isLoading } = useDrillFiltersCount(item, onSetup);
    const drillFilterButtonLabel = intl.formatMessage({
        id: "configurationPanel.drillConfig.filterSelection.button.withCount",
    }, {
        count: selectedFiltersCount,
    });
    const { widgetRef } = item;
    const widgetDrills = useDashboardSelector(selectWidgetDrills(widgetRef));
    invariant(widgetRef, "mush have widget selected");
    const { isFromDateAttribute, showDateFilterTransferWarning } = useDateAttributeOptions(item, widgetRef);
    const drillTargetTypeItems = disableDrillDownIfMeasure(enabledDrillTargetTypeItems, item.type === "measure", intl);
    const isAllowedDrillTypeForDrillIntersectionIgnoredAttributes = compact([
        DRILL_TARGET_TYPE.DRILL_TO_DASHBOARD,
        DRILL_TARGET_TYPE.DRILL_TO_INSIGHT,
        DRILL_TARGET_TYPE.DRILL_DOWN,
    ]).some((drillTarget) => drillTarget === item?.drillTargetType);
    const showDrillConfigButton = (item.drillTargetType === DRILL_TARGET_TYPE.DRILL_DOWN &&
        isDrillDownToAttributeHierarchyConfig(item) &&
        !!item.attributeHierarchyRef) ||
        (item.drillTargetType === DRILL_TARGET_TYPE.DRILL_TO_INSIGHT &&
            isDrillToInsightConfig(item) &&
            !!item.insightRef) ||
        (item.drillTargetType === DRILL_TARGET_TYPE.DRILL_TO_DASHBOARD &&
            isDrillToDashboardConfig(item) &&
            !!item.dashboard);
    const showDrillIntersectionIgnoredAttributes = isAllowedDrillTypeForDrillIntersectionIgnoredAttributes;
    const onDrillIntersectionIgnoredAttributesChange = (ignoredAttributeLocalIds) => {
        const targetDrill = widgetDrills.find((d) => d.localIdentifier === item.localIdentifier);
        const currentIgnoredAttributes = item.drillIntersectionIgnoredAttributes ?? [];
        const isDrillDown = item.drillTargetType === DRILL_TARGET_TYPE.DRILL_DOWN;
        const isChanged = !isEqual(currentIgnoredAttributes, ignoredAttributeLocalIds);
        if (isDrillDown && isChanged) {
            const drillDownItem = {
                attributeHierarchyRef: item.attributeHierarchyRef,
                type: "drillDownAttributeHierarchy",
                attributes: item.attributes,
                originLocalIdentifier: item.originLocalIdentifier,
                drillIntersectionIgnoredAttributes: ignoredAttributeLocalIds,
            };
            onSetup(drillDownItem, {
                ...item,
                drillIntersectionIgnoredAttributes: ignoredAttributeLocalIds,
            }, true);
        }
        else if (targetDrill && isChanged) {
            onSetup({
                ...targetDrill,
                drillIntersectionIgnoredAttributes: ignoredAttributeLocalIds,
            }, {
                ...item,
                drillIntersectionIgnoredAttributes: ignoredAttributeLocalIds,
            });
        }
    };
    return (_jsxs("div", { className: classNames, children: [
            _jsx("div", { className: "drill-config-item-intro", children: _jsx(FormattedMessage, { id: "configurationPanel.drillConfig.clickHintItem", values: {
                        addon: (chunks) => _jsx("span", { className: "addon", children: chunks }),
                    } }) }), _jsx(DrillOriginItem, { type: item.type, title: item.title, onDelete: onDeleteClick, isDateAttribute: isFromDateAttribute }), _jsx("div", { className: targetClassNames, children: _jsxs("div", { className: "drill-config-target-box", children: [
                        _jsx("div", { className: "drill-config-item-target", children: _jsx(FormattedMessage, { id: "configurationPanel.drillConfig.selectTarget" }) }), _jsx(DrillTargetType, { onSelect: onDrillTargetTypeSelect, selection: item.drillTargetType, enabledDrillTargetTypeItems: drillTargetTypeItems, isButtonDisabled: false }), _jsx(DrillTargets, { item: item, onSetup: onSetup, onDeleteInteraction: onDeleteClick }), isDrillFiltersConfigEnabled ? (showDrillConfigButton ? (_jsx(DrillFiltersTrigger, { label: drillFilterButtonLabel, isLoading: isLoading, onClick: () => openDrillFilters(item.localIdentifier) })) : null) : showDrillIntersectionIgnoredAttributes ? (_jsx(DrillIntersectionIgnoredAttributes, { drillTargetType: item.drillTargetType, item: item, onChange: onDrillIntersectionIgnoredAttributesChange })) : null, !!item.warning && (_jsxs("div", { className: "drill-config-target-warning s-drill-config-target-warning", children: [
                                _jsx("span", { className: "gd-icon-warning" }), _jsx("span", { children: _jsx(FormattedMessage, { id: item.warning }) })
                            ] })), showDateFilterTransferWarning ? (_jsx("div", { className: "drill-config-date-filter-warning s-drill-config-date-filter-warning", children: _jsx("span", { children: _jsx(FormattedMessage, { id: "configurationPanel.drillConfig.drillIntoDashboard.dateFilterWarning" }) }) })) : null] }) })
        ] }));
}
function useDateAttributeOptions(item, widgetRef) {
    const dateAttributes = useDashboardSelector(selectCatalogDateDatasets);
    const drillTargets = useDashboardSelector(selectDrillTargetsByWidgetRef(widgetRef));
    return useMemo(() => {
        const attributeTarget = drillTargets?.availableDrillTargets?.attributes?.find((attribute) => attribute.attribute.attributeHeader.localIdentifier === item.originLocalIdentifier);
        const isFromDateAttribute = !!(attributeTarget &&
            isAttributeDescriptor(attributeTarget.attribute) &&
            dateAttributes.some((attribute) => attribute.dateAttributes.some((dateAttribute) => areObjRefsEqual(dateAttribute.attribute.ref, attributeTarget.attribute.attributeHeader.formOf.ref))));
        const isDateAttributeInIntersection = item.type === "measure" &&
            item.attributes.some((attr) => dateAttributes.some((x) => x.dateAttributes.some((d) => areObjRefsEqual(d.attribute.ref, attr.attributeHeader.ref))));
        const showDateFilterTransferWarning = item.drillTargetType === DRILL_TARGET_TYPE.DRILL_TO_DASHBOARD &&
            (isFromDateAttribute || isDateAttributeInIntersection);
        return {
            isFromDateAttribute,
            isDateAttributeInIntersection,
            showDateFilterTransferWarning,
        };
    }, [
        drillTargets?.availableDrillTargets?.attributes,
        dateAttributes,
        item.type,
        item.attributes,
        item.drillTargetType,
        item.originLocalIdentifier,
    ]);
}
//# sourceMappingURL=InsightDrillConfigItem.js.map