import { FormikValues } from 'formik'
import _isEmpty from 'lodash/isEmpty'
import _map from 'lodash/map'

import { isBrowser } from '../../../../utils'
import { combineValidators, requiredValidator } from '../../../../validators'

export const getValidateFunctions = ({
  element,
  values,
}: {
  element: IFormField;
  values: FormikValues;
}) => {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const validationFunctions: any[] = []
  if (element.required) {
    validationFunctions.push(requiredValidator)
  }

  if (element.onValidate) {
    validationFunctions.push(element.onValidate)
  }

  if (element.name === 'confirmEmail') {
    const isSameEmail = (confirmEmail?: string) =>
      values.email !== confirmEmail
        ? 'Please confirm your email address correctly'
        : null
    validationFunctions.push(isSameEmail)
  }

  if (element.name === 'confirmPassword') {
    const isSame = (confirmPassword?: string) =>
      values.password !== confirmPassword
        ? 'Password confirmation does not match'
        : null

    validationFunctions.push(isSame)
  }

  return combineValidators(...validationFunctions)
}

export const updateFormFieldsAttributes = (
  formFields: IFormFieldsSection[],
  attributes?: IFieldAttribute
) => {
  if (attributes && !_isEmpty(attributes)) {
    const updatedFormFields = _map(formFields, fieldSection => {
      const fieldSectionAttributes = attributes[fieldSection.name] || {}

      const updatedFields = _map(fieldSection.fields, fieldItem => {
        const fieldItemAttributes = attributes[fieldItem.name] || {}
        return { ...fieldItem, ...fieldItemAttributes }
      })

      return {
        ...fieldSection,
        ...fieldSectionAttributes,
        fields: updatedFields,
      }
    })

    return updatedFormFields
  }
  return formFields
}

export const getFieldClassNames = (id: string, existingClassNames: string) => {
  if (isBrowser) {
    const elem = document && document.getElementById(id)

    if ((elem?.parentElement?.clientWidth || 0) < 375) {
      return existingClassNames + ' full-width'
    }
  }

  return existingClassNames
}

export const insertHTML = (elementId: string, text = '') => {
  if (isBrowser) {
    const elem = document && document.getElementById(elementId)

    if (!elem?.childNodes.length) {
      elem?.insertAdjacentHTML('afterbegin', text)
    }
  }

  return null
}
