import React, { useEffect } from "react";

interface TextFieldProps extends React.InputHTMLAttributes<HTMLInputElement> {
  value?: any;
  label?: string;
  options?: Array<string>;
  onChange?: any; //(e: React.ChangeEvent<HTMLInputElement>) => void,
  //onChangeElement?:(e:React.ChangeEvent<HTMLSelectElement>) => void
  inputType?: string;
  keyform?: string;
  error?: string;
  className?: string;
}

const TextField = (props: TextFieldProps) => {
  let {
    value,
    label,
    options,
    placeholder,
    onChange,
    inputType,
    keyform,
    error,
    className,
  } = props;

  useEffect(() => {
    if (inputType === "select" && options?.length === 0) {
      throw Error("Provea opciones para su select");
    }
  });

  let inputSelector;
  switch (inputType) {
    case "select":
      inputSelector = (
        <select
          className={error ? "input_error" : className}
          onChange={onChange}
          name=""
          id=""
          defaultValue={value? value : 'DEFAULT'} 
        >
          <option value={'DEFAULT'} disabled hidden>
          Seleccionar una opción
          </option>
          {options?.map((option, index) => {
            return (
              <option key={index} value={option}>
                {option}
              </option>
            );
          })}
        </select>
      );
      break;
    case "radio":
      inputSelector = (
        <div className={"radio-group"}>
          {options?.map((option, index) => {
            return (
              <div className={"radio-item"}>
                <input type={"radio"} name={label} key={index} value={option} />
                <label>{option}</label>
              </div>
            );
          })}
        </div>
      );
      break;
    default:
      inputSelector = (
        <input
          {...props}
          className={error ? "input_error" : className}
          placeholder={placeholder}
          onChange={onChange}
        />
      );
  }

  return (
    <div className="field" key={keyform}>
      {label && <label style={{ paddingBottom: "8px" }}>{label}</label>}
      {inputSelector}
      {error && <div className="small text-red ">{error}</div>}
    </div>
  );
};

export default TextField;
