import { useCallback } from "react";

import { useBanner } from "../../contexts/banner.js";

import type { Checkbox } from "../../components/common/checkbox.js";
import type { VisualServiceGroup } from "../../types/service.js";
import type { ComponentProps } from "react";

function useGroupCheckbox(group: VisualServiceGroup) {
    const banner = useBanner();
    const { id, items, isEssential } = group;
    const { previewCheckboxActiveState, consent, activeAction } = banner;

    const isDisabled = isEssential || activeAction === "history";
    const isChecked = previewCheckboxActiveState || isEssential || !!consent[id];
    const isPartial =
        !isEssential &&
        consent[id]?.length &&
        JSON.stringify(items.map(({ id }) => id).sort()) !== JSON.stringify(consent[id].sort() || []);

    const onToggle: ComponentProps<typeof Checkbox>["onToggle"] = useCallback(
        (checked) => banner.updateGroupChecked(id, checked),
        [banner, id, isChecked],
    );

    return { isDisabled, isChecked, isPartial, onToggle };
}

export { useGroupCheckbox };
