import { useCallback, useState } from "react";

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

import { useStylesheet } from "../../contexts/stylesheet.js";
import { AsciiSpinner } from "../asciiSpinner.js";

import type { FC, HTMLAttributes } from "react";

const Button: FC<
    {
        type: "acceptAll" | "acceptEssentials" | "acceptIndividual" | "save";
        busyOnClick?: boolean;
        forceShow?: boolean;
        framed?: boolean;
        sticky?: boolean;
    } & HTMLAttributes<HTMLElement>
> = ({ type, children, busyOnClick = true, forceShow, onClick, framed, sticky, className, ...rest }) => {
    const {
        buttons: { [type]: Button },
        framed: framedClass,
        stickyButton: stickyClass,
        forceShowButton: forceShowButtonClassName,
    } = useStylesheet().extend(...extendCommonButtonsStylesheet);

    const [isBusy, setIsBusy] = useState(false);
    const handleOnClick: HTMLAttributes<HTMLAnchorElement>["onClick"] = useCallback(
        (e) => {
            if (!isBusy) {
                e.preventDefault();
                busyOnClick && setIsBusy(true);
                onClick?.(e);
            }
        },
        [onClick, isBusy, busyOnClick],
    );

    return (
        <Button
            onClick={handleOnClick}
            onKeyDown={(e) => {
                if (e.code.toLowerCase() === "space") {
                    (e.target as HTMLElement).click();
                }
            }}
            className={[
                framed ? framedClass : undefined,
                sticky ? stickyClass : undefined,
                forceShow ? forceShowButtonClassName : undefined,
                className,
            ]
                .filter(Boolean)
                .join(" ")}
            role="button"
            {...rest}
        >
            <span>{isBusy ? <AsciiSpinner /> : children}</span>
        </Button>
    );
};

export { Button };
