import React from "react";
import { RadioButtonProps } from "./types";

import { Button } from "@shared/components/button";
import { cx } from "@shared/utils";

export const RadioButton: React.FC<RadioButtonProps> = props => {
  const {
    name,
    value,
    label,
    subText,
    checked,
    onChange,
    className,
    variant = "circle",
    hasError = false,
    labelProps = {},
    "data-cy": dataCy,
    labelClassName = "",
    disabled,
    ...rest
  } = props;

  const handleChange = () => onChange?.(value || name);

  return (
    <label
      htmlFor={name}
      className={cx("flex items-center", className)}
      data-cy={dataCy}
      {...labelProps}
    >
      <input
        className="hidden"
        type="radio"
        name={name}
        value={value}
        checked={checked}
        readOnly
        disabled={disabled}
        {...rest}
      />
      <Button
        type="button"
        onClick={handleChange}
        disabled={disabled}
        className={cx(
          "mr-3 flex h-6 w-6 flex-shrink-0 items-center justify-center rounded-full border-[1px] border-solid border-border-secondary-on-bg-fill bg-bg outline-offset-4",
          checked && "border-[1px] border-solid border-border-brand",
          disabled && "opacity-50"
        )}
      >
        {checked && (
          <div className="h-[0.875rem] w-[0.875rem] rounded-full bg-bg-fill-brand" />
        )}
      </Button>
      <Button
        type="button"
        onClick={handleChange}
        disabled={disabled}
        tabIndex={label ? 0 : -1}
      >
        <div className={cx("text-body2 font-normal", labelClassName)}>
          {label}
        </div>
        <div className="text-body1 text-text-info">{subText}</div>
      </Button>
    </label>
  );
};

RadioButton.displayName = "RadioButton";

export type { RadioButtonProps };
