import { Radio as FlowbiteRadio, Label } from "flowbite-react";
import { FC, useId } from "react";
import { useFormContext } from "react-hook-form";

type Props = {
  groupLabel: string;
  name: string;
  errors?: any;
  labelCls?: string;
  options: { [key: string]: number | string }[];
  defaultValue?: string | number | undefined;
  flex?: boolean;
};

export const Radio: FC<Props> = ({
  groupLabel,
  name,
  errors,
  labelCls,
  options,
  defaultValue = undefined,
  flex = true,
  ...props
}) => {
  const { register } = useFormContext();
  const id = useId();
  return (
    <>
      <div className="max-w-md">
        <div className={`mb-2 block ${labelCls}`}>
          <Label htmlFor={id} value={groupLabel} />
        </div>
        <div className={`${flex ? "flex" : ""}`}>
          {options?.map((option, index) => (
            <div key={index}>
              <FlowbiteRadio
                id={`radio-${name}-${index}`}
                {...register(name)}
                {...props}
                value={option?.value}
                defaultChecked={defaultValue === option?.value}
              />
              <Label className="ml-2 mr-2" htmlFor={`radio-${name}-${index}`}>
                {option?.label}
              </Label>
            </div>
          ))}
        </div>
      </div>
    </>
  );
};
