// FieldNumberText.tsx
import React, { forwardRef } from 'react';
import { Controller, useFormContext } from 'react-hook-form';
import TextField from '@mui/material/TextField';

interface FieldNumberTextProps {
  name: string;
  label?: string;
  readOnly?: boolean;
  sx?: any;
}

const FieldNumberText = forwardRef<HTMLInputElement, FieldNumberTextProps>(
  ({ name, label, readOnly = false, sx, ...props }, ref) => {
    const { control } = useFormContext();

    const formatNumber = (value: string | number) => {
      if (value === undefined || value === null || value === '') return '';
      const numStr = value.toString().replace(/\D/g, '');
      return numStr.replace(/\B(?=(\d{3})+(?!\d))/g, '.');
    };

    const parseNumber = (value: string) => value.replace(/\./g, '');

    return (
      <Controller
        name={name}
        control={control}
        render={({ field, fieldState }) => (
          <TextField
            {...field}
            {...props}
            ref={ref}
            label={label}
            value={formatNumber(field.value)}
            onChange={(e) => field.onChange(parseNumber(e.target.value))}
            fullWidth
            InputProps={{
              readOnly,
            }}
            sx={{
              backgroundColor: readOnly ? '#f6f6f6' : 'inherit',
              ...sx,
            }}
            error={!!fieldState.error?.message}
            helperText={fieldState.error?.message}
          />
        )}
      />
    );
  }
);

FieldNumberText.displayName = 'FieldNumberText';
export default FieldNumberText;
