import _isArray from 'lodash/isArray'
import _isEmpty from 'lodash/isEmpty'

import { CustomFieldOption, CustomFieldTypes } from '../index'

const getLabelForValue = (options: CustomFieldOption[], value: string | string[]): string => {
  const getLabel = (singleValue: string) => {
    const option = options.find(option => option.value === singleValue)
    return option ? option.name : ''
  }

  if (_isArray(value)) {
    const labels = value.map(getLabel)
    return labels.join(', ')
  }

  return getLabel(value as string)
}

export const renderCustomFieldValue = (customField: CustomFieldTypes) => {
  if (customField.type === 'checkbox') {
    return customField.value ? 'Checked' : 'Unchecked'
  }

  if (_isEmpty(customField.value)) {
    return 'N/A'
  }

  if (customField.type === 'select' || customField.type === 'select_multi' || customField.type === 'radio') {
    return getLabelForValue(customField.options as CustomFieldOption[], customField.value)
  }

  return customField.value
}

export const isFieldUpdatable = (field: CustomFieldTypes): boolean => {
  if (!field?.settings?.allowUpdate || (field?.type === 'checkbox' && field?.required)) {
    return false
  }
  return true
}

export const createCustomFieldsUpdateBody = (
  updatedValues: Record<string, any>,
  notUpdatableCustomFieldsValues: Array<CustomFieldTypes> = []
) =>
  notUpdatableCustomFieldsValues.reduce(
    (acc, customField) => {
      if (!isFieldUpdatable(customField)) {
        acc[customField.name] = customField.value
      }
      return acc
    },
    { ...updatedValues }
  )
