import { Label, Select as SelectOption } from "flowbite-react";
import { FC, useId } from "react";
import { useFormContext } from "react-hook-form";

type Props = {
  labelText?: string;
  name: string;
  errors?: any;
  labelCls?: string;
  placeholder?: string;
  options: { [key: string | number]: number | string | boolean }[];
  defaultOption?: string | null;
  defaultValue?: string | number | undefined;
  onChange?: (e: any) => void;
  size?: string;
};

export const Select: FC<Props> = ({
  labelText = undefined,
  name,
  errors,
  labelCls,
  placeholder = "",
  options,
  defaultOption = null,
  defaultValue = undefined,
  onChange = () => {},
  size = "md",
  ...props
}) => {
  const { register } = useFormContext();
  const id = useId();
  return (
    <>
      <div className="w-full">
        {labelText && (
          <div className={`mb-2 block ${labelCls}`}>
            <Label htmlFor={id} value={labelText} />
          </div>
        )}
        <SelectOption
          id={id}
          sizing={size}
          {...props}
          {...register(name)}
          defaultValue={defaultValue}
          onChange={(e) => onChange(e)}
          className="select-field"
          helperText={
            errors && (
              <>
                <span className="text-red-500">{errors?.[name]?.message}</span>
              </>
            )
          }
        >
          {defaultOption && <option value={0}>{defaultOption}</option>}
          {options?.map((option, index) => (
            <option key={index} value={option.value}>
              {option.label}
            </option>
          ))}
        </SelectOption>
      </div>
    </>
  );
};
