import { useCallback } from "react";

import { useBanner } from "../../../contexts/banner.js";
import { Cookie } from "../../common/groups/cookie.js";

import type { VisualService, VisualServiceGroup } from "../../../types/service.js";
import type { ComponentProps, FC } from "react";

const BannerCookie: FC<{ group: VisualServiceGroup; cookie: VisualService }> = ({
    group: { id: groupId, isEssential },
    cookie,
}) => {
    const { id } = cookie;
    const banner = useBanner();
    const { consent, activeAction } = banner;

    const isDisabled = isEssential || activeAction === "history";
    const isChecked = isEssential || (consent?.[groupId] || []).some((c) => c === id);

    const handleCheckbox: ComponentProps<typeof Cookie>["onToggle"] = useCallback(
        (checked) => banner.updateCookieChecked(groupId, id, checked),
        [banner, groupId, id],
    );

    return (
        <Cookie
            cookie={cookie}
            propertyListProps={{ isEssentialGroup: isEssential }}
            checked={isChecked}
            disabled={isDisabled}
            onToggle={handleCheckbox}
        />
    );
};

export { BannerCookie };
