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

const CheckBox = ({
  name,
  label,
  classNameInput,
  classNameContent,
  classNameLabel,
  ...others
}: {
  name: string
  label?: string
  classNameInput?: string
  classNameContent?: string
  classNameLabel?: string
  [others: string]: unknown
}) => {
  const {
    control,
    formState: { errors }
  } = useFormContext()

  const { field } = useController({
    name,
    control
  })

  return (
    <div className="flex flex-col">
      <div className={`${classNameContent} flex mb-4 items-center`}>
        <input
          {...others}
          className={`${classNameInput}  w-4 h-4 bg-gray-100 accent-primary-500 border-gray-300 rounded focus:ring-primary-500 dark:focus:ring-primary-800 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600`}
          type="checkbox"
          checked={field.value}
          onChange={field.onChange}
        />
        <label
          className={`${classNameLabel}   ml-2 text-sm font-medium text-gray-900 dark:text-gray-300" htmlFor="default-checkbox`}
          htmlFor={name}
        >
          {label}
        </label>
      </div>
      {errors[name] && <ErrorSpan>{errors[name]?.message?.toString()}</ErrorSpan>}
    </div>
  )
}

export default CheckBox
