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;
  disableFormat?: boolean;
  decimalScale?: number;
  maxValue?: number;
  minValue?: number;
  readOnly?: boolean;
  negativeMask?: 'prefix' | 'suffix' | 'both';
  [key: string]: any;
  displayOnly?: boolean;
};

export function RHFNumeric({
  name,
  label,
  allowNegativeValue = false,
  allowDecimalValue = false,
  disableFormat = false,
  decimalScale = 0,
  maxValue,
  minValue,
  readOnly,
  displayOnly = false,
  negativeMask = 'prefix',
  ...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}
          disabled={readOnly && !displayOnly}
          onChange={(e) => {
            if (readOnly || displayOnly) return;

            const constrainedValue = handleValueChange(e.target.value);
            // kalau mau number -> field.onChange(Number(constrainedValue));
            field.onChange(constrainedValue);
          }}
          // InputProps={{

          //   inputComponent: disableFormat
          //     ? undefined // ⛔ tanpa format rupiah
          //     : !allowNegativeValue
          //       ? NumberFormatRupiah
          //       : NumberFormatRupiahWithAllowedNegative,
          //   readOnly,
          //   inputProps: {
          //     allowNegativeValue,
          //     allowDecimalValue,
          //     decimalScale,
          //     fixedDecimalScale: false,
          //     maxValue,
          //     minValue,
          //   },
          //   ...props.InputProps,
          // }}

          InputProps={{
            ...props.InputProps,

            // kalau displayOnly → readonly beneran tapi tetep aktif format
            readOnly: displayOnly ? true : props.InputProps?.readOnly,

            inputComponent: disableFormat
              ? undefined
              : !allowNegativeValue
                ? NumberFormatRupiah
                : NumberFormatRupiahWithAllowedNegative,

            inputProps: {
              ...props.InputProps?.inputProps,
              allowNegativeValue,
              allowDecimalValue,
              decimalScale,
              fixedDecimalScale: false,
              maxValue,
              minValue,

              // format-component butuhkan ini agar tidak error
              valueIsNumericString: true,
              negativeMask,
            },

            style: displayOnly
              ? {
                  pointerEvents: 'none',
                  backgroundColor: '#f6f6f6',
                  ...(props.InputProps?.style || {}),
                }
              : props.InputProps?.style,
          }}
          error={!!fieldState.error}
          helperText={fieldState.error?.message}
          sx={{
            input: {
              textAlign: 'right',
              ...(readOnly && {
                backgroundColor: '#f6f6f6',
                color: '#1C252E',
                WebkitTextFillColor: '#1C252E',
              }),
            },

            // === Disabled normal (tanpa error) ===
            ...(readOnly && {
              '& .MuiOutlinedInput-root.Mui-disabled:not(.Mui-error)': {
                backgroundColor: '#f6f6f6',
                '& .MuiInputBase-input.Mui-disabled': {
                  WebkitTextFillColor: '#1C252E',
                  color: '#1C252E',
                },
              },
              '& .MuiInputLabel-root.Mui-disabled:not(.Mui-error)': {
                color: '#1C252E',
              },
            }),

            // === Disabled + Error (prioritas lebih tinggi) ===
            '& .MuiOutlinedInput-root.Mui-disabled.Mui-error .MuiOutlinedInput-notchedOutline': {
              borderColor: (theme) => theme.palette.error.main,
            },
            '& .MuiInputLabel-root.Mui-disabled.Mui-error': {
              color: (theme) => theme.palette.error.main,
            },
            '& .MuiFormHelperText-root.Mui-error': {
              color: (theme) => theme.palette.error.main,
            },
          }}
          {...props}
        />
      )}
    />
  );
}
