import React from "react";
import { startCase } from "lodash-es";

interface Option {
  value: string;
  label: string;
  description?: string;
}

interface RadioInputProps {
  fieldName: string;
  register: any;
  required?: boolean;
  options: (string | Option)[];
  withDescription?: boolean;
  defaultChecked?: string;
  onChangeFn?: (value: string, index: number) => void;
}

const RadioInput: React.FC<RadioInputProps> = ({
  fieldName,
  register,
  required = false,
  options,
  withDescription = false,
  defaultChecked = "",
  onChangeFn,
}) => {
  return (
    <div className="grid grid-cols-2 gap-2 justify-start items-center w-fit">
      {options.map((option, index) => {
        const value = typeof option === "object" ? option.value : option;
        const label = typeof option === "object" ? option.label : option;
        const description =
          typeof option === "object" && withDescription
            ? option.description
            : null;
        return (
          <div
            className={`flex justify-start items-center gap-1.5 rounded-full w-fit border-2 border-slate-200 py-1 px-3 ${
              typeof option === "object" ? "" : ""
            }`}
            key={index}
          >
            <input
              type="radio"
              id={index}
              value={value}
              defaultChecked={value === defaultChecked}
              {...register(fieldName, {
                required: required ? "This field is required." : false,
              })}
              onClick={() => onChangeFn && onChangeFn(value, index)}
            />
            <label htmlFor={label}>
              {startCase(label)} <p>{description}</p>
            </label>
          </div>
        );
      })}
    </div>
  );
};

export default RadioInput;
