import { Field, Label, Select as HeadlessSelect } from '@headlessui/react'
import { type ComponentProps, type ReactNode } from 'react'
import {
  get,
  type FieldError,
  type FieldValues,
  type Path,
  type RegisterOptions,
} from 'react-hook-form'
import { useRemixFormContext } from 'remix-hook-form'

type TInputProperties<T extends FieldValues> = Omit<
  ComponentProps<'select'>,
  'size'
> & {
  id: string
  label?: ReactNode
  name: Path<T>
  rules?: RegisterOptions
  placeholder?: string
  options?: {
    code: string
    name: string
    id: string
  }[]
}

export const Select = <TFormValues extends Record<string, unknown>>(
  properties: TInputProperties<TFormValues>,
) => {
  const { id, label, name, rules, disabled, placeholder, options, ...rest } =
    properties

  const {
    register,
    formState: { errors },
  } = useRemixFormContext()

  const error: FieldError = get(errors, name)

  return (
    <Field
      className="relative"
      disabled={disabled}
      id={id}
    >
      <Label className="mb-1 block text-gray-700">
        {label} {error && <span className="text-red-500">{error.message}</span>}
      </Label>
      <HeadlessSelect
        className="focus:inheriten h-[42px] w-full rounded-md border border-[#DFDFDF] p-2"
        {...register(name, rules)}
        {...rest}
      >
        <option value="">{placeholder}</option>
        {options?.map(({ id, name }) => (
          <option
            key={id}
            value={id}
          >
            {name}
          </option>
        ))}
      </HeadlessSelect>
    </Field>
  )
}
