'use client';
import { ReactNode } from 'react';
import TextField, { TextFieldProps } from '@mui/material/TextField';
import { Controller, FieldValues, RegisterOptions, useFormContext } from 'react-hook-form';
import type { RhfFieldProps } from './types';

export type RhfTextFieldProps<TFieldValues extends FieldValues> = RhfFieldProps<TFieldValues> &
  Omit<TextFieldProps, 'name' | 'value' | 'onChange' | 'onBlur' | 'error' | 'defaultValue' | 'inputRef'> & {
    /**
     * Normalizes raw keystrokes before they reach form state — digit stripping, max length, locale
     * digit folding. Applying it here (rather than in each screen's `onChange`) is what keeps the
     * *stored* value canonical instead of merely the *displayed* one.
     */
    transform?: (raw: string) => string;
    /** Shown below the field whenever there is no validation error to show instead. */
    helperText?: ReactNode;
  };

/**
 * `TextField` bound to a react-hook-form field.
 *
 * Every form in this app used to hold one `useState` per input plus a parallel `useState` per error
 * flag, which re-rendered the entire screen — including price previews, query-backed cards and
 * uploaders — on every keystroke, and left validation scattered across ad-hoc `if` blocks in each
 * submit handler. `Controller` subscribes only this field to its own value and error, so a keystroke
 * re-renders one input; the rules travel with the field they validate.
 *
 * Reads `control` from `FormProvider` when it isn't passed explicitly, so a form only wires it once.
 * @component RhfTextField
 */
const RhfTextField = <TFieldValues extends FieldValues>({
  name,
  control,
  rules,
  transform,
  helperText,
  ...textFieldProps
}: RhfTextFieldProps<TFieldValues>) => {
  const context = useFormContext<TFieldValues>();
  const resolvedControl = control ?? context?.control;

  return (
    <Controller
      name={name}
      control={resolvedControl}
      rules={rules as RegisterOptions<TFieldValues>}
      render={({ field, fieldState }) => (
        <TextField
          {...textFieldProps}
          name={field.name}
          inputRef={field.ref}
          value={field.value ?? ''}
          onChange={(event) => field.onChange(transform ? transform(event.target.value) : event.target.value)}
          onBlur={field.onBlur}
          error={Boolean(fieldState.error)}
          helperText={fieldState.error?.message ?? helperText}
        />
      )}
    />
  );
};

export default RhfTextField;
