import React, { useState } from "react";
import PropTypes from "prop-types";
import {
  Container,
  RadioControl,
  RadioInput,
  RadioLabel,
  RadioWrapper,
} from "./styles";

const Radio = ({
  options,
  defaultValue,
  onChange,
  direction,
  ...props
}) => {
  const [value, setValue] = useState(defaultValue);

  const handleChange = (event) => {
    const newValue = event.target.value;
    setValue(newValue);
    onChange && onChange(newValue);
  };

  return (
    <Container direction={direction} {...props}>
      {options.map((option) => (
        <RadioWrapper key={option.value}>
          <RadioInput
            id={option.value}
            name="radio-group"
            value={option.value}
            checked={value === option.value}
            onChange={handleChange}
            {...props}
          />
          <RadioControl {...props}></RadioControl>
          <RadioLabel
            htmlFor={option.value}
            checked={value === option.value}
            {...props}
          >
            {option.label}
          </RadioLabel>
        </RadioWrapper>
      ))}
    </Container>
  );
};

Radio.propTypes = {
  options: PropTypes.arrayOf(
    PropTypes.shape({
      value: PropTypes.oneOfType([PropTypes.string, PropTypes.number])
        .isRequired,
      label: PropTypes.string.isRequired,
    })
  ).isRequired,
  defaultValue: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  onChange: PropTypes.func,
  direction: PropTypes.oneOf(["row", "column"]),
};

Radio.defaultProps = {
    defaultValue: null,
    direction: 'row'
};

export default Radio;
