import React, { SelectHTMLAttributes } from 'react';
import { UseFormRegisterReturn, ControllerRenderProps } from 'react-hook-form';
import { formService } from '../../../services/form.service';

export interface AppSelectOption {
  value: string;
  label: string;
}

export interface AppSelectProps extends Omit<SelectHTMLAttributes<HTMLSelectElement>, 'name'> {
  label: string;
  options: AppSelectOption[];
  error?: { type: string; message?: string; [key: string]: any } | undefined;
  register?: UseFormRegisterReturn;
  // For use with Controller
  field?: ControllerRenderProps<any, any>;
  placeholder?: string;
}

export function AppSelect({
  label,
  options,
  error,
  register,
  field,
  placeholder = '',
  className = '',
  ...selectProps
}: AppSelectProps): JSX.Element {
  const hasError = !!error;
  const selectClassName = `w-full ${hasError ? 'border-error' : ''} ${className}`.trim();

  return (
    <label className="block flex flex-col gap-2">
      <span className="text-xs font-medium">{label}</span>
      <select
        {...(register || field || {})}
        className={selectClassName}
        {...selectProps}
      >
        {placeholder && <option value="">{placeholder}</option>}
        {options.map((option) => {
          const { value, label } = option;
          return (
            <option key={value} value={value}>
              {label}
            </option>
          );
        })}
      </select>
      {error && <p className="text-error">{formService.getErrorMessage(error)}</p>}
    </label>
  );
}
