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}
          //   FormHelperTextProps={{ sx: { color: 'error.main' } }}
          //   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',
          //       },
          //     }),
          //   }}

          //   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',
          //       },
          //     }),

          //     // ✅ tambahan untuk kondisi error
          //     '& .Mui-error': {
          //       color: (theme) => theme.palette.error.main,
          //     },
          //     '& .MuiOutlinedInput-root.Mui-error .MuiOutlinedInput-notchedOutline': {
          //       borderColor: (theme) => theme.palette.error.main,
          //     },
          //     '& .MuiFormHelperText-root.Mui-error': {
          //       color: (theme) => theme.palette.error.main,
          //     },
          //   }}

          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}
        />
      )}
    />
  );
}
