// (C) 2025-2026 GoodData Corporation
import { useCallback } from "react";
import { areObjRefsEqual, dashboardAttributeFilterItemDisplayForm, isAttributeDescriptor, isResultAttributeHeader, } from "@gooddata/sdk-model";
import { useIdPrefixed } from "@gooddata/sdk-ui-kit";
import { useAttribute } from "../../hooks/useAttribute.js";
import { useKdaState } from "../../providers/KdaState.js";
import { clearSummaryValue, createNewAttributeFilter, updateExistingAttributeFilter } from "../../utils.js";
export function useDrillAttributeHandler() {
    const { state, setState } = useKdaState();
    const attributeFinder = useAttribute();
    const id = useIdPrefixed("attr_id_");
    const onDrillCallback = useCallback((event) => {
        const attribute = event.drillContext.intersection
            ?.map((i) => i.header)
            .filter(isAttributeDescriptor)[0];
        const attributeItem = event.drillContext.intersection
            ?.map((i) => i.header)
            .filter(isResultAttributeHeader)[0];
        if (!attribute) {
            return;
        }
        if (!attributeItem) {
            return;
        }
        const currentFilters = state.attributeFilters;
        const catalogAttribute = attributeFinder(attribute.attributeHeader.ref);
        if (!catalogAttribute) {
            return;
        }
        const found = currentFilters.find((f) => areObjRefsEqual(dashboardAttributeFilterItemDisplayForm(f), catalogAttribute.attribute.ref) ||
            catalogAttribute.displayForms.some((df) => areObjRefsEqual(df.ref, dashboardAttributeFilterItemDisplayForm(f))));
        const value = attributeItem.attributeHeaderItem.uri;
        const primaryDisplayForm = catalogAttribute.displayForms.find((df) => df.isPrimary)?.ref;
        if (found) {
            const newFilters = state.attributeFilters.map((f) => {
                if (found === f) {
                    return updateExistingAttributeFilter(f, value, primaryDisplayForm);
                }
                return f;
            });
            setState({
                attributeFilters: newFilters,
                ...clearSummaryValue(state.definition),
            });
        }
        else {
            setState({
                attributeFilters: [
                    ...state.attributeFilters,
                    createNewAttributeFilter(catalogAttribute, attribute.attributeHeader.ref, id, value),
                ],
                ...clearSummaryValue(state.definition),
            });
        }
    }, [attributeFinder, id, setState, state.attributeFilters, state.definition]);
    return {
        onDrillCallback,
    };
}
//# sourceMappingURL=useDrillAttributeHandler.js.map