import { CircularProgress } from '@mui/material'
import _get from 'lodash/get'
import _identity from 'lodash/identity'
import React, { useEffect, useState } from 'react'

import { getCustomFields } from '../../api'
import {
  getDataWithCustomFields,
  getFieldsKeys,
  getQueryVariable,
} from '../../utils'
import { getAddOnDataWithCustomFields } from '../../utils/customFields'

const withCustomFields = (Children: any) => (props: any) => {
  const {
    data = [],
    ticketHoldersFields = {
      id: 1,
      fields: [],
    },
    skipCustomFields = true,
    onGetCustomFieldsError = _identity,
    onGetCustomFieldsSuccess = _identity,
    ...args
  } = props

  const [lodaing, setLoading] = useState(!skipCustomFields)
  const [customFieldsData, setCustomFieldsData] = useState({} as any)
  const [customFieldsOrderKeys, setCustomFieldsOrderKeys] = useState([] as any)
  const [customFieldsTicketHolderKeys, setCustomFieldsTicketHolderKeys] = useState([] as any)
  const [customFieldsAddOnKeys, setCustomFieldsAddOnKeys] = useState([] as any)

  const getFields = async () => {
    try {
      const eventId = getQueryVariable('event_id') || getQueryVariable("eventId") || ''
      const customFields = await getCustomFields(eventId)

      const orderFieldsKeys = getFieldsKeys(_get(customFields, 'orderFields', []))
      const ticketHoldersFieldsKeys = getFieldsKeys(_get(customFields, 'ticketsFields', []))
      const addOnFieldsKeys = getFieldsKeys(_get(customFields, 'addOnFields', []))

      setCustomFieldsTicketHolderKeys(ticketHoldersFieldsKeys)
      setCustomFieldsOrderKeys(orderFieldsKeys)
      setCustomFieldsData(customFields)
      setCustomFieldsAddOnKeys(addOnFieldsKeys)

      onGetCustomFieldsSuccess(customFields)
    } catch (e) {
      onGetCustomFieldsError(e)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    if (!skipCustomFields) {
      getFields()
    }
  }, [])

  const {
    dataWithCustomFields,
    ticketHoldersWithCustomFields,
  } = getDataWithCustomFields(data, ticketHoldersFields, customFieldsData)

  const { addOnDataWithCustomFields } = getAddOnDataWithCustomFields(customFieldsData)

  if (lodaing) {
    return <CircularProgress size={50} />
  }

  return (
    <Children
      {...args}
      data={dataWithCustomFields}
      ticketHoldersFields={ticketHoldersWithCustomFields}
      customFieldsOrderKeys={customFieldsOrderKeys}
      customFieldsTicketHolderKeys={customFieldsTicketHolderKeys}
      customFieldsAddOnKeys={customFieldsAddOnKeys}
      addOnDataWithCustomFields={addOnDataWithCustomFields}
    />
  )
}

export { withCustomFields }
