import { useController, useFormContext } from 'react-hook-form'
import { ErrorSpan } from './ErrorSpan'

const Input = ({
  name,
  label,
  type,
  placeholder,
  className,
  classNameContent,
  ...others
}: {
  name: string
  label?: string
  type?: string
  placeholder?: string
  className?: string
  classNameContent?: string
  [others: string]: unknown
}) => {
  const {
    control,
    formState: { errors }
  } = useFormContext()

  const { field } = useController({
    name,
    control
  })
  console.log(field.name)

  return (
    <div className={`${classNameContent}`}>
      <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor={name}>
        {label}
      </label>
      <input
        {...field}
        {...others}
        className={`${className} shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-1 focus:shadow-outline`}
        type={type}
        placeholder={placeholder}
      />
      {errors[name] && <ErrorSpan>{errors[name]?.message?.toString()}</ErrorSpan>}
    </div>
  )
}

export default Input
