import { CheckOutlined, MinusOutlined } from "@ant-design/icons-svg";
import { Fragment } from "react";

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

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

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

const Checkbox: FC<
    {
        hideCheckbox?: boolean;
        isChecked: boolean;
        onToggle?: (state: boolean) => void;
        isPartial?: boolean;
        isDisabled?: boolean;
        fontSize: number;
        after?: ReactNode;
    } & Omit<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, "onChange" | "onClick">
> = ({
    hideCheckbox,
    isPartial,
    isChecked,
    isDisabled,
    fontSize,
    onToggle,
    children,
    after,
    "aria-describedby": ariaDescribedby,
    ...rest
}) => {
    const {
        checkbox: { className, style },
        Label,
    } = useStylesheet().extend(...extendCommonStylesheet);
    const CheckboxIcon = isPartial ? MinusOutlined : CheckOutlined;

    const handleChange: HTMLAttributes<HTMLInputElement>["onChange"] = (e) => {
        const { checked } = e.target as HTMLInputElement;
        onToggle?.(checked);
    };

    return (
        <Label>
            {!hideCheckbox && (
                <Fragment>
                    <input
                        name="checkbox[]"
                        type="checkbox"
                        value="1"
                        checked={isChecked}
                        disabled={isDisabled}
                        className={className}
                        style={style({ fontSize })}
                        onChange={handleChange}
                        aria-describedby={ariaDescribedby}
                    />
                    <PlainAntdIconAsSvg aria-hidden icon={CheckboxIcon} {...rest} />
                </Fragment>
            )}
            {children && (
                <span>
                    <span>{children}</span>
                    {after && (
                        <span
                            onClick={(e) => {
                                // Do not modify the checkbox
                                e.stopPropagation();
                            }}
                        >
                            {after}
                        </span>
                    )}
                </span>
            )}
        </Label>
    );
};

export { Checkbox };
