// (C) 2020-2026 GoodData Corporation
import { useCallback, useMemo, useState } from "react";
import { isEqual } from "lodash-es";
import { DataViewFacade, isSomeHeaderPredicateMatched, } from "@gooddata/sdk-ui";
import { addDrillTargets } from "../../../../../model/commands/drillTargets.js";
import { useDashboardDispatch, useDashboardSelector, } from "../../../../../model/react/DashboardStoreProvider.js";
import { selectAccessibleDashboardsLoaded } from "../../../../../model/store/accessibleDashboards/accessibleDashboardsSelectors.js";
import { selectCatalogIsLoaded } from "../../../../../model/store/catalog/catalogSelectors.js";
import { selectDrillTargetsByWidgetRef } from "../../../../../model/store/drillTargets/drillTargetsSelectors.js";
import { selectIsInEditMode } from "../../../../../model/store/renderMode/renderModeSelectors.js";
import { selectConfiguredAndImplicitDrillsByWidgetRef, selectDrillableItemsByWidgetRef, } from "../../../../../model/store/widgetDrills/widgetDrillSelectors.js";
/**
 * @internal
 */
export const useDashboardInsightDrills = ({ widget, insight, onDrill: onDrillFn, }) => {
    const dispatch = useDashboardDispatch();
    const drillTargets = useDashboardSelector(selectDrillTargetsByWidgetRef(widget.ref));
    const disableDrillDownOnWidget = insight.insight.properties["controls"]?.["disableDrillDown"];
    const catalogIsLoaded = useDashboardSelector(selectCatalogIsLoaded);
    const accessibleDashboardsLoaded = useDashboardSelector(selectAccessibleDashboardsLoaded);
    const [isLoadingDrillTargets, setIsLoadingDrillTargets] = useState(true);
    const onPushData = useCallback((data) => {
        const targets = data?.availableDrillTargets;
        if (targets && !isEqual(drillTargets?.availableDrillTargets, targets)) {
            dispatch(addDrillTargets(widget.ref, targets));
        }
        if ("availableDrillTargets" in data) {
            setIsLoadingDrillTargets(false);
        }
    }, [drillTargets, widget.ref, dispatch]);
    const isInEditMode = useDashboardSelector(selectIsInEditMode);
    const rawDrillableItems = useDashboardSelector(selectDrillableItemsByWidgetRef(widget.ref));
    const drillableItems = useMemo(() => {
        return isInEditMode ? [] : rawDrillableItems;
    }, [isInEditMode, rawDrillableItems]);
    const implicitDrillDefinitions = useDashboardSelector(selectConfiguredAndImplicitDrillsByWidgetRef(widget.ref));
    const onDrill = onDrillFn
        ? (event) => {
            const facade = DataViewFacade.for(event.dataView);
            const matchingImplicitDrillDefinitions = implicitDrillDefinitions.filter((info) => {
                const isDrillDownDisabled = disableDrillDownOnWidget && info.drillDefinition.type === "drillDown";
                return (!isDrillDownDisabled &&
                    event.drillContext.intersection?.some((intersection) => isSomeHeaderPredicateMatched(info.predicates, intersection.header, facade)));
            });
            const drillEvent = {
                ...event,
                widgetRef: widget.ref,
                drillDefinitions: matchingImplicitDrillDefinitions.map((info) => info.drillDefinition),
            };
            return (typeof onDrillFn === "function" &&
                onDrillFn(drillEvent, {
                    insight,
                    widget,
                }));
        }
        : undefined;
    // disable all drills until necessary items are loaded
    const drillActive = catalogIsLoaded && accessibleDashboardsLoaded && !isLoadingDrillTargets;
    return {
        drillableItems: drillActive ? drillableItems : [],
        onPushData,
        onDrill,
    };
};
