import { Controller, useFormContext } from 'react-hook-form';
import { TextField } from '@mui/material';
import NumberFormatRupiahWithAllowedNegative from '../NumberFormatRupiahWithAllowedNegative/NumberFormatRupiahWithAllowedNegative';
import NumberFormatRupiah from '../NumberFormatRupiah';

type RHFNumericProps = {
  name: string;
  label: string;
  allowNegativeValue?: boolean;
  allowDecimalValue?: boolean;
  maxValue?: number;
  minValue?: number;
  readOnly?: boolean;
  [key: string]: any;
};

export function RHFNumeric({
  name,
  label,
  allowNegativeValue = false,
  allowDecimalValue = false,
  maxValue,
  minValue,
  readOnly,
  ...props
}: RHFNumericProps) {
  const { control } = useFormContext();

  const handleValueChange = (value: string) => {
    const numericValue = Number(value.replace(/[^\d.-]/g, ''));
    let finalValue = value;

    if (!isNaN(numericValue)) {
      if (maxValue !== undefined && numericValue > maxValue) {
        finalValue = maxValue.toString();
      }
      if (minValue !== undefined && numericValue < minValue) {
        finalValue = minValue.toString();
      }
    }

    return finalValue;
  };

  return (
    <Controller
      name={name}
      control={control}
      render={({ field, fieldState }) => (
        <TextField
          {...field}
          label={label}
          fullWidth
          variant="outlined"
          value={field.value ?? ''}
          disabled={readOnly}
          onChange={(e) => {
            const constrainedValue = handleValueChange(e.target.value);
            // kalau mau number -> field.onChange(Number(constrainedValue));
            field.onChange(constrainedValue);
          }}
          InputProps={{
            inputComponent: !allowNegativeValue
              ? NumberFormatRupiah
              : NumberFormatRupiahWithAllowedNegative,
            readOnly,
            inputProps: {
              allowNegativeValue,
              allowDecimalValue,
              maxValue,
              minValue,
            },
            ...props.InputProps,
          }}
          error={!!fieldState.error}
          helperText={fieldState.error?.message}
          sx={{
            input: {
              textAlign: 'right',
              ...(readOnly && {
                backgroundColor: '#f6f6f6',
                color: '#1C252E',
                WebkitTextFillColor: '#1C252E',
              }),
            },
            ...(readOnly && {
              '& .MuiInputLabel-root': {
                color: '#1C252E',
              },
              '& .Mui-disabled': {
                WebkitTextFillColor: '#1C252E',
                color: '#1C252E',
                opacity: 1,
                backgroundColor: '#f6f6f6',
              },
            }),
          }}
          {...props}
        />
      )}
    />
  );
}
