'use client';
import { ReactNode } from 'react';
import { FormHelperText, FormLabel, Stack, Typography } from '@mui/material';
import { Controller, ControllerRenderProps, FieldValues, RegisterOptions, useFormContext } from 'react-hook-form';
import type { RhfFieldProps } from './types';

export type RhfControlGroupProps<TFieldValues extends FieldValues> = RhfFieldProps<TFieldValues> & {
  /** Already-translated group label. */
  label?: string;
  /** Already-translated one-line hint under the label. */
  hint?: string;
  /**
   * Renders the actual control. `field` is react-hook-form's binding (`value`/`onChange`/`onBlur`);
   * `hasError` lets a control that carries its own error styling (`GenderToggle`) reflect it.
   */
  children: (args: { field: ControllerRenderProps<TFieldValues>; hasError: boolean }) => ReactNode;
};

/**
 * Binds an arbitrary non-input control — `GenderToggle`, `RelationSelect`, `RatingInput`, a map-pin
 * picker — to a react-hook-form field, and gives it the same label/hint/error-message shell the
 * `TextField`-based wrappers get for free.
 *
 * Without it these controls kept their own `useState` plus a hand-rolled `xxxError` boolean and a
 * bespoke error `<Typography>` per screen, which is exactly the pattern that made "is this form
 * valid?" un-answerable from one place.
 * @component RhfControlGroup
 */
const RhfControlGroup = <TFieldValues extends FieldValues>({
  name,
  control,
  rules,
  label,
  hint,
  children,
}: RhfControlGroupProps<TFieldValues>) => {
  const context = useFormContext<TFieldValues>();
  const resolvedControl = control ?? context?.control;

  return (
    <Controller
      name={name}
      control={resolvedControl}
      rules={rules as RegisterOptions<TFieldValues>}
      render={({ field, fieldState }) => (
        <Stack sx={{ gap: 1 }}>
          {label ? <FormLabel error={Boolean(fieldState.error)}>{label}</FormLabel> : null}
          {hint ? (
            <Typography variant="caption" sx={{ color: 'text.secondary' }}>
              {hint}
            </Typography>
          ) : null}
          {children({ field: field as ControllerRenderProps<TFieldValues>, hasError: Boolean(fieldState.error) })}
          {fieldState.error?.message ? <FormHelperText error>{fieldState.error.message}</FormHelperText> : null}
        </Stack>
      )}
    />
  );
};

export default RhfControlGroup;
