import React, { HTMLProps } from "react";
import classNames from "classnames";
import { useId } from "@reach/auto-id";
import { Box } from "../Box";
import { Input } from "../Input";
import { Text } from "../Text";
import { Icon, ICON_TYPE } from "../Icon";
import { bem } from "../../utilities/bem";
import isUndefined from "../../utilities/isUndefined";

const cn = "OptionButton";

interface OptionButtonProps extends HTMLProps<HTMLInputElement> {
  heading: string;
  description?: string;
}

export const OptionButton = (props: OptionButtonProps) => {
  const {
    heading,
    description,
    id: idProp,
    checked,
    className,
    defaultValue,
    ...rest
  } = props;

  const fallbackId = `OptionButton:${useId()}`;
  const id = isUndefined(idProp) ? fallbackId : idProp;

  return (
    <Box as="label" className={classNames(bem(cn), className)}>
      <Box className={bem(cn, { e: "content" })}>
        {heading && (
          <Text as="div" className={bem(cn, { e: "heading" })}>
            {heading}
          </Text>
        )}

        {description && (
          <Text as="div" className={bem(cn, { e: "description" })}>
            {description}
          </Text>
        )}
      </Box>

      <Input
        id={id}
        type="radio"
        checked={checked}
        className={bem(cn, { e: "input" })}
        defaultValue={defaultValue}
        aria-checked={checked ? "true" : "false"}
        {...rest}
      />

      <Box className={bem(cn, { e: "backdrop" })} />

      <Box className={bem(cn, { e: "selected" })}>
        <Icon className={bem(cn, { e: "icon" })} icon={ICON_TYPE.CHECK} />
        Selected
      </Box>
    </Box>
  );
};
