import _get from 'lodash/get'
import _identity from 'lodash/identity'
import React, { FC, useEffect, useState } from 'react'

import { getCustomerExistsData } from '../../api/guestTicketDelegation'
import { Loader } from '../../components/common'
import { LoginForm } from '../../components/loginForm'
import { RegistrationForm } from '../../components/registerForm'
import { useCookieListener } from '../../hooks/useCookieListener'
import { getCookieByName, getQueryVariable } from '../../utils'
import IssueComponent from './IssueComponent'

interface IRegistrationProps {
  registerFormFields?: Array<IFormFieldsSection>;
  classNamePrefix?: string;
  logo?: string;
  onCustomerExistsError?: (error: any) => void;
  issuePageErrorText?: string;
}

const X_TF_ECOMMERCE = 'X-TF-ECOMMERCE'

export const DelegationsContainer: FC<IRegistrationProps> = ({
  registerFormFields,
  classNamePrefix = 'guest-ticket-delegation',
  issuePageErrorText = 'You do not have access to manage these tickets.',
  onCustomerExistsError = _identity,
  logo,
}) => {
  const [loading, setLoading] = useState(true)
  const [isLoggedIn, setIsLoggedIn] = useState(Boolean(getCookieByName(X_TF_ECOMMERCE)))
  const [isCustomerExsists, setIsCustomerExsists] = useState(false)
  const [issuePageError, setIssuePageError] = useState(false)
  const [customerEmail, setCustomerEmail] = useState('')
  const accessHash = getQueryVariable('hash') || ''

  useCookieListener(X_TF_ECOMMERCE, value => setIsLoggedIn(Boolean(value)))

  const onGetIssuePageDataError = () => {
    setIssuePageError(true)
  }

  useEffect(() => {
    const getCustomerData = async () => {
      try {
        const response = await getCustomerExistsData(accessHash)
        const isCustomerExsists = _get(response, 'data.attributes.customerExists', false)
        setIsCustomerExsists(isCustomerExsists)
        setCustomerEmail(_get(response, 'data.attributes.email', ''))
        setLoading(false)
      } catch (error) {
        onCustomerExistsError(error)
      }
    }

    getCustomerData()
  }, [])

  return (
    <div className={`${classNamePrefix}__container`}>
      {loading ? (
        <Loader />
      ) : issuePageError ? (
        <div className="issue_page_error">{issuePageErrorText}</div>
      ) : isLoggedIn ? (
        <div>
          <IssueComponent
            classNamePrefix={classNamePrefix}
            onGetIssuePageDataError={onGetIssuePageDataError}
          />
        </div>
      ) : isCustomerExsists ? (
        <LoginForm logo={logo} />
      ) : (
        <RegistrationForm
          customerEmail={customerEmail}
          formFields={registerFormFields}
          registrationType="delegation"
        />
      )}
    </div>
  )
}
