import { REDUX_ERROR_PROP_NAME } from '@/modules/@common/Form/constants';

const flatErrorsKeys = (obj, parentKey = '', result = {}) => {
  for (const key in obj) {
    if (Array.isArray(obj[key])) {
      if (obj[key].length > 0 && typeof obj[key][0] === 'object') {
        obj[key].forEach((item, index) => {
          flatErrorsKeys(item, `${parentKey}.${key}.${index}`, result);
        });
      } else {
        // eslint-disable-next-line no-param-reassign
        result[`${parentKey}.${key}`] = obj[key];
      }
    } else if (typeof obj[key] === 'object' && obj[key] !== null) {
      flatErrorsKeys(obj[key], `${parentKey}.${key}`, result);
    } else {
      // eslint-disable-next-line no-param-reassign
      result[`${parentKey}.${key}`] = obj[key];
    }
  }

  return result;
};

export const getErrorFieldsList = (validationResult) => {
  const errors = [];

  validationResult.forEach((item) => {
    if (item.dynamic) {
      Object.entries(flatErrorsKeys(item[REDUX_ERROR_PROP_NAME], item.fieldName)).forEach(([fieldName, value]) => {
        if (value) {
          errors.push({
            ...item,
            fieldName,
            [REDUX_ERROR_PROP_NAME]: value,
          });
        }
      });
    } else if (item[REDUX_ERROR_PROP_NAME]) {
      errors.push(item);
    }
  });

  return errors;
};

export const getRequiredInputProps = ({ fieldName, label, error = false, helperText = '' }) => ({
  required: true,
  label: label ?? 'Required',
  name: fieldName,
  error: !!error,
  helperText: helperText || '',
});

export const getInputPropsByName = (scheme, fieldArray, customLabel) => {
  const fieldName = fieldArray.join('.');
  const errorData = getErrorFieldsList(scheme).find((error) => error.fieldName === fieldName) ?? {};

  return getRequiredInputProps({
    label: customLabel,
    fieldName,
    error: !!errorData[REDUX_ERROR_PROP_NAME],
    helperText: errorData[REDUX_ERROR_PROP_NAME],
  });
};
