import { useState } from "react";

import { yieldLazyLoad } from "@devowl-wp/react-utils";
import { extendBlockerBodyStylesheet } from "@devowl-wp/web-cookie-banner";

import { useBlocker } from "../../../contexts/blocker.js";
import { useBlockerMissingServices } from "../../../hooks/blocker/useBlockerMissingServices.js";
import { useBlockerStylesheet } from "../../../hooks/blocker/useBlockerStylesheet.js";
import { useCommonTeachings } from "../../../hooks/common/useTeachings.js";
import { useA11yId } from "../../../hooks/useA11yId.js";
import { BodyDescription } from "../../common/body/description.js";
import { Button } from "../../common/button.js";

import type { FC } from "react";

const Cookie = yieldLazyLoad(
    import(/* webpackChunkName: "banner-lazy", webpackMode: "lazy-once" */ "../../common/groups/cookie.js").then(
        ({ Cookie }) => Cookie,
    ),
);

const BlockerBody: FC = () => {
    const {
        Container,
        CookieScroll,
        a11yIds: { firstButton },
    } = useBlockerStylesheet().extend(...extendBlockerBodyStylesheet);

    const blocker = useBlocker();
    const a11yCookieList = useA11yId();
    const [areCookiesVisible, setCookiesVisible] = useState(false);
    const {
        texts: { blockerLoadButton, blockerLinkShowMissing, blockerAcceptInfo },
        onUnblock,
        productionNotice,
        isConsentRecord,
        i18n: { close },
    } = blocker;
    const missing = useBlockerMissingServices();

    const { description, teachings } = useCommonTeachings({
        services: missing,
        // Not needed in blocker, as there is already a link with "Show all services which I need to consent to"
        disableListServicesNotice: true,
        disableTcfPurposes: true,
    });

    return (
        <Container>
            <div>
                <BodyDescription description={description} teachings={[...teachings, blockerAcceptInfo]} nl2br />
                <Button
                    id={firstButton}
                    type="acceptIndividual"
                    onClick={() => setCookiesVisible(!areCookiesVisible)}
                    forceShow
                    busyOnClick={false}
                    aria-expanded={areCookiesVisible}
                    aria-controls={a11yCookieList}
                >
                    {areCookiesVisible ? close : blockerLinkShowMissing}
                </Button>
                <CookieScroll>
                    {areCookiesVisible &&
                        missing.map((cookie) => <Cookie key={cookie.id} cookie={cookie} checked disabled />)}
                </CookieScroll>
                <Button type="acceptAll" onClick={(e) => onUnblock(e)} forceShow sticky busyOnClick={!isConsentRecord}>
                    {blockerLoadButton}
                </Button>
                {productionNotice}
            </div>
        </Container>
    );
};

export { BlockerBody };
