import { CaretDownFilled, CaretRightFilled, DownOutlined, RightOutlined } from "@ant-design/icons-svg";
import { useMemo } from "react";

import { findUsedDeclarations } from "@devowl-wp/cookie-consent-web-client";

import { useBanner } from "../../../contexts/banner.js";
import { AccordionItem, AccordionList } from "../../common/accordionItem.js";

import type { FC } from "react";

const BannerTcfStacks: FC = () => {
    const banner = useBanner();
    const {
        tcf: { gvl, model },
        texts: { tcfStacksCustomName, tcfStacksCustomDescription },
        bodyDesign: { accordionArrowType },
        isListServicesNotice,
    } = banner;
    const {
        vendors,
        stacks,
        purposes: { 1: purpose1 },
    } = gvl;

    // Always show Purpose #1 in initial layer, but first check if it is generally in use
    const usesPurpose1 = useMemo(() => {
        const legInt = findUsedDeclarations("purposes", gvl, model, "legInt").filter(({ id }) => id === 1);
        const consent = findUsedDeclarations("purposes", gvl, model, "consent").filter(({ id }) => id === 1);
        return legInt.length > 0 || consent.length > 0;
    }, [vendors, gvl, model]);

    const icon =
        accordionArrowType !== "none"
            ? accordionArrowType === "filled"
                ? CaretRightFilled
                : RightOutlined
            : undefined;
    const iconExpanded =
        accordionArrowType !== "none" ? (accordionArrowType === "filled" ? CaretDownFilled : DownOutlined) : undefined;

    return (
        <AccordionList>
            {usesPurpose1 && (
                <AccordionItem title={purpose1.name} icon={icon} iconExpanded={iconExpanded}>
                    {purpose1.description}
                </AccordionItem>
            )}
            {Object.values(stacks).map(({ id, name, description }) => (
                <AccordionItem key={id} title={name} icon={icon} iconExpanded={iconExpanded}>
                    {description}
                </AccordionItem>
            ))}
            {!isListServicesNotice && (
                <AccordionItem title={tcfStacksCustomName} icon={icon} iconExpanded={iconExpanded}>
                    {tcfStacksCustomDescription}
                </AccordionItem>
            )}
        </AccordionList>
    );
};

export { BannerTcfStacks };
