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

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

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

const GroupButton: FC<{
    legend: string;
    active: string;
    onChange: (key: string) => void;
    items: Array<{ key: string; value: string }>;
}> = ({ legend, active, onChange, items }) => {
    const { ButtonGroup, buttonGroupItem, screenReaderOnlyClass, Label } = useStylesheet().extend(
        ...extendCommonStylesheet,
    );
    const a11yName = useA11yId();

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

    return (
        <ButtonGroup>
            <legend className={screenReaderOnlyClass}>{legend}</legend>
            {items.map(({ key, value }) => (
                <Label key={key}>
                    <input
                        name={a11yName}
                        type="radio"
                        value={key}
                        checked={active === key}
                        className={buttonGroupItem}
                        aria-label={value}
                        onChange={handleChange}
                    />
                    <span aria-hidden>{value}</span>
                </Label>
            ))}
        </ButtonGroup>
    );
};

export { GroupButton };
