import React from "react";
import cn from "classnames";
import PropTypes from "prop-types";
import Tooltip from "../../tooltip/tooltip";
import TooltipInner from "../../tooltip/tooltip-inner";
import { IRadioButtonGroupProps } from "./radio-button.d";
import RadioButton from "./radio-button";
import Form from "../form-tags";

const RadioButtonGroup = (props: IRadioButtonGroupProps) => {
  const {
    onSelected,
    selection,
    buttons,
    defaultValue,
    inline,
    error,
    help,
    label,
    name,
    disabledReason,
    globalDisabled,
    escapeHelpContent
  } = props;
  const selectedItem = selection === undefined ? defaultValue : selection;
  const testId = props["data-testid"] || "honeyui-radio-group";

  return (
    <Form.Group className="position-relative">
      {globalDisabled && disabledReason && (
        <Tooltip
          reference={<div className="position-absolute w-100 h-100" style={{ zIndex: 2 }} />}
          placement="top"
        >
          <TooltipInner className="mw-100">
            <span>{disabledReason} </span>
          </TooltipInner>
        </Tooltip>
      )}
      <Form.LabelTag data-testid={`${testId}-label`}>{label}</Form.LabelTag>

      <div className={cn({ "is-invalid": error })}>
        {buttons &&
          buttons.map((b, i) => (
            <RadioButton
              data-testid={`${testId}-${b.value}`}
              key={String(b.value)}
              onSelected={onSelected}
              checked={selectedItem === b.value}
              inline={inline}
              globalDisabled={globalDisabled}
              {...b}
            />
          ))}
      </div>

      <Form.HelpTag data-testid={`${testId}-help`} name={name} escapeContent={escapeHelpContent}>
        {help}
      </Form.HelpTag>
      <Form.ErrorTag data-testid={`${testId}-error`} name={name}>
        {error}
      </Form.ErrorTag>
    </Form.Group>
  );
};

RadioButtonGroup.displayName = "RadioButtonGroup";

RadioButtonGroup.defaultProps = {
  buttons: [],
  defaultValue: "",
  inline: false,
  onSelected: () => {}
};

RadioButtonGroup.propTypes = {
  buttons: PropTypes.arrayOf(
    PropTypes.shape({
      className: PropTypes.string,
      name: PropTypes.string.isRequired,
      value: PropTypes.oneOfType([PropTypes.number, PropTypes.string, PropTypes.bool]).isRequired,
      label: PropTypes.string.isRequired
    })
  ),
  defaultValue: PropTypes.oneOfType([PropTypes.number, PropTypes.string, PropTypes.bool]),
  error: PropTypes.string,
  help: PropTypes.string,
  inline: PropTypes.bool,
  label: PropTypes.string,
  name: PropTypes.string,
  onSelected: PropTypes.func,
  selection: PropTypes.oneOfType([PropTypes.number, PropTypes.string, PropTypes.bool]),
  escapeHelpContent: PropTypes.bool
};

export default RadioButtonGroup;
