import { useState } from "react";

import { extendCommonStylesheet } from "@devowl-wp/web-cookie-banner";

import { useStylesheet } from "../../contexts/stylesheet.js";
import { useA11yId } from "../../hooks/useA11yId.js";
import { PlainAntdIconAsSvg } from "../plainAntdIconAsSvg.js";

import type { ComponentProps, FC, PropsWithChildren } from "react";

type IconDefinition = ComponentProps<typeof PlainAntdIconAsSvg>["icon"];

const AccordionList: FC<PropsWithChildren> = ({ children }) => {
    const { AccordionList } = useStylesheet().extend(...extendCommonStylesheet);
    return <AccordionList>{children}</AccordionList>;
};

const AccordionItem: FC<
    PropsWithChildren<{
        title: string;
        icon?: IconDefinition;
        iconExpanded?: IconDefinition;
        expandable?: boolean;
    }>
> = ({ children, title, icon, iconExpanded, expandable = true }) => {
    const {
        accordionArrow,
        AccordionDescription,
        AccordionItem,
        AccordionButton,
        AccordionTitle,
        accordionItemActive,
        accordionItemDisabled,
    } = useStylesheet().extend(...extendCommonStylesheet);
    const [expanded, setExpanded] = useState(false);
    const a11yExpanded = useA11yId();

    return (
        <AccordionItem
            onClick={() => expandable && setExpanded(!expanded)}
            className={[expanded && accordionItemActive, !expandable && accordionItemDisabled]
                .filter(Boolean)
                .join(" ")}
        >
            <AccordionButton
                {...(expandable ? {} : { disabled: "disabled" })}
                aria-expanded={expanded}
                aria-controls={a11yExpanded}
                href="#"
                onClick={(e) => e.preventDefault()}
            >
                {!!icon && (
                    <PlainAntdIconAsSvg
                        icon={expanded && !!iconExpanded ? iconExpanded : icon}
                        className={accordionArrow}
                    />
                )}
                <AccordionTitle>{title}</AccordionTitle>
            </AccordionButton>
            <div id={a11yExpanded}>
                {expanded && expandable && <AccordionDescription>{children}</AccordionDescription>}
            </div>
        </AccordionItem>
    );
};

export { AccordionList, AccordionItem };
