import React, { useEffect, useState } from 'react';

export interface IRadioItems {
  label: string;
  value: string;
}

export interface IRadioProps {
  name: string;
  items: IRadioItems[];
  onChange: (value: string) => void;
}

export const InputRadio: React.FC<IRadioProps> = ({
  name,
  items,
  onChange,
}) => {
  const [selectedValue, setSelectedValue] = useState<string>();
  const handleClick = () => {
    let element = document.querySelector(
      `input[name=${name}]:checked`
    ) as HTMLInputElement;
    const elementValue = element.value;
    setSelectedValue(elementValue);
  };

  useEffect(() => {
    if (selectedValue) {
      onChange(selectedValue);
    }
  }, [selectedValue]);

  return (
    <div id="elemento-radio">
      {items.map(element => {
        return (
          <>
            <input
              key={element.value}
              className="rpgui-radio"
              value={element.value}
              name={name}
              type="radio"
            />
            <label onPointerDown={handleClick}>{element.label}</label>
            <br />
          </>
        );
      })}
    </div>
  );
};
