import React, {
  FunctionComponent,
  ReactNode,
  useEffect,
  useState,
} from "react";
import { Radio } from "../Radio";

import "./styles.scss";

export interface IOption {
  label: ReactNode;
  value: string | number;
}

interface IRadioListProps {
  label?: string;
  options?: IOption[];
  selectedValue?: string | number;
  disabled?: boolean;
  onChange?: (option: string | number) => void;
  name?: string;
  orientation?: "vertical" | "horizontal";
  warning?: string;
  error?: string;
  isValid?: boolean;
}

export const RadioList: FunctionComponent<IRadioListProps> = (props) => {
  const {
    label,
    options = [],
    error,
    warning,
    orientation = "vertical",
    onChange,
    disabled,
    name,
    selectedValue,
    isValid,
  } = props;

  const [selected, setSelected] = useState(selectedValue);

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

  const containerClassName = `c-radio-list c-radio-list--${orientation} ${!isValid ? "c-radio-list--invalid" : ""}`;

  return (
    <div className={containerClassName}>
      {label && <div className="c-radio-list__label">{label}</div>}
      <div className="c-radio-list__list">
        {options.map((option) => (
          <Radio
            key={option.value}
            name={name}
            disabled={disabled}
            onChange={(checked) => {
              checked && setSelected(option.value);
              onChange?.(option.value);
            }}
            label={option.label}
            checked={option.value === selected}
          />
        ))}
      </div>
      {error && <div className="c-radio-list__validation">{error}</div>}
      {warning && <div className="c-radio-list__warning">{warning}</div>}
    </div>
  );
};
