import {
  Controller,
  type FieldValues,
  type Path,
  type RegisterOptions,
  useFormContext,
} from "react-hook-form";

import { FileDropZone } from "../FileDropZone.tsx";

interface FileFieldProps<T extends FieldValues> {
  name: Path<T>;
  label?: string;
  hint?: string;
  showLimit?: boolean;
  disabled?: boolean;
  rules?: RegisterOptions<T, Path<T>>;
}

/** `Controller`-wrapped {@link FileDropZone} bound to react-hook-form. */
export function FileField<T extends FieldValues>({
  name,
  label,
  hint,
  showLimit,
  disabled,
  rules,
}: FileFieldProps<T>) {
  const { control, formState: { errors } } = useFormContext<T>();
  const error = errors[name];

  return (
    <div className="form-field">
      <Controller
        name={name}
        control={control}
        rules={rules}
        render={({ field }) => (
          <FileDropZone
            file={(field.value as File | null) ?? null}
            onChange={field.onChange}
            label={label}
            hint={hint}
            showLimit={showLimit}
            disabled={disabled}
          />
        )}
      />
      {error?.message && (
        <span className="form-hint form-hint--error">
          {String(error.message)}
        </span>
      )}
    </div>
  );
}
