'use client';
import { Controller, FieldValues, RegisterOptions, useFormContext } from 'react-hook-form';
import JalaliDateField, { JalaliDateFieldProps } from '../JalaliDateField';
import type { RhfFieldProps } from './types';

export type RhfJalaliDateFieldProps<TFieldValues extends FieldValues> = RhfFieldProps<TFieldValues> &
  Omit<JalaliDateFieldProps, 'name' | 'value' | 'onChange' | 'error' | 'helperText'> & {
    helperText?: string;
  };

/**
 * `JalaliDateField` bound to a react-hook-form field. Stores the wire ISO (Gregorian) `YYYY-MM-DD`
 * string the picker emits, or `null` — the same shape every date on the wire uses.
 * @component RhfJalaliDateField
 */
const RhfJalaliDateField = <TFieldValues extends FieldValues>({
  name,
  control,
  rules,
  helperText,
  ...fieldProps
}: RhfJalaliDateFieldProps<TFieldValues>) => {
  const context = useFormContext<TFieldValues>();
  const resolvedControl = control ?? context?.control;

  return (
    <Controller
      name={name}
      control={resolvedControl}
      rules={rules as RegisterOptions<TFieldValues>}
      render={({ field, fieldState }) => (
        <JalaliDateField
          {...fieldProps}
          name={field.name}
          value={(field.value as string | null) ?? null}
          onChange={field.onChange}
          error={Boolean(fieldState.error)}
          helperText={fieldState.error?.message ?? helperText}
        />
      )}
    />
  );
};

export default RhfJalaliDateField;
