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

export interface AppInputProps extends Omit<InputHTMLAttributes<HTMLInputElement>, 'name'> {
  label: string;
  error?: { type: string; message?: string; [key: string]: any } | undefined;
  register?: UseFormRegisterReturn;
  // For use with Controller
  field?: {
    name: string;
    value: string;
    onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
    onBlur: () => void;
    ref: React.Ref<HTMLInputElement>;
  };
}

export function AppInput({
  type = 'text',
  label,
  error,
  register,
  field,
  className = '',
  ...inputProps
}: AppInputProps): JSX.Element {
  const hasError = !!error;
  const inputClassName = `w-full ${hasError ? 'border-error' : ''} ${className}`.trim();

  return (
    <label className="block flex flex-col gap-2">
      <span className="text-xs font-medium">{label}</span>
      <input
        type={type}
        {...(register || field || {})}
        className={inputClassName}
        {...inputProps}
      />
      {error && <p className="text-error">{formService.getErrorMessage(error)}</p>}
    </label>
  );
}