import "./style.css"

import { ThemeOptions } from '@mui/material'
import { createTheme, ThemeProvider } from '@mui/material/styles'
import { CSSProperties } from '@mui/styles'
import axios, { AxiosError } from 'axios'
import _get from 'lodash/get'
import _identity from 'lodash/identity'
import _isEmpaty from 'lodash/isEmpty'
import React, { FC, useEffect, useState } from 'react'

import {
  getPreRegistrationInfluencers,
  getPreRegistrationShareOptions,
} from '../../api/preRegistrationComplete'
import { X_TF_ECOMMERCE } from '../../constants'
import { useCookieListener } from '../../hooks'
import { getCookieByName, getQueryVariable } from '../../utils'
import { CopyMessageModal } from '../common'
import ConfirmModal from '../confirmModal'
import { LoginModal } from '../loginModal'
import { Prewards } from './Prewards'
import { ShareOptions } from './ShareOptions'

const isWindowDefined = typeof window !== 'undefined'

export const PreRegistrationComplete: FC<
  IPreRegistrationCompleteProps & {
    onGetConfirmationDataError?: (error: AxiosError) => void;
    skipInitialValidation?: boolean;
    themeOptions?: ThemeOptions & {
      input?: CSSProperties;
      checkbox?: CSSProperties;
    };
  }
> = ({
  eventId: pEventId,
  classNamePrefix = '',
  onLinkCopied = _identity,
  hasCopyIcon = false,
  pageHeader = 'Pre-Registration Confirmation',
  onGetConfirmationDataError = _identity,
  onGetConfirmationDataSuccess = _identity,
  pageMessage = 'Pre registration was successful!',
  onLoginSuccess = _identity,
  logo,
  themeOptions,
  skipInitialValidation = false,
}) => {
    const themeMui = createTheme(themeOptions)

    const localStorageHash = isWindowDefined
      ? localStorage.getItem('pre-registration-hash')
      : ''
    const queryHash = getQueryVariable('hash') || ''
    queryHash &&
      isWindowDefined &&
      window.localStorage.setItem('pre-registration-hash', queryHash)
    const hash = queryHash || localStorageHash
    const [isLoggedIn, setIsLoggedIn] = useState(Boolean(getCookieByName(X_TF_ECOMMERCE)))
    const [showModalLogin, setShowModalLogin] = useState(!isLoggedIn)
    const [showCopyModal, setShowCopyModal] = useState(false)
    const [prizes, setPrizes] = useState([] as Array<IPrizeData>)
    const [shareOptions, setShareOptions] = useState({} as IShareOptionsData)
    const [shareActionData, setShareActionData] = useState(
      {} as ISubmitShareActionAttributes
    )
    const [error, setError] = useState({} as AxiosError)
    useCookieListener(X_TF_ECOMMERCE, value => setIsLoggedIn(Boolean(value)))
    useEffect(() => {
      const fetchConfirmationData = async () => {
        // Skip validation if this is a freshly completed pre-registration
        if (skipInitialValidation) {
          onGetConfirmationDataSuccess()
          return
        }

        try {
          if (hash && isLoggedIn) {
            const shareOptionsData = await getPreRegistrationShareOptions({
              hash,
            })
            const { attributes } = shareOptionsData.data
            setShareOptions(shareOptionsData.data)
            setShareActionData({
              shareActionToken: attributes.shareActionToken,
              tokenShuffleMethod: attributes.tokenShuffleMethod,
            })
            const eventId = _get(shareOptionsData, 'data.attributes.eventId')
            if (eventId || pEventId) {
              const influencersData = await getPreRegistrationInfluencers({
                eventId: eventId || pEventId,
              })
              setPrizes(influencersData.data.attributes.prizes)
            }
            onGetConfirmationDataSuccess()
          }
        } catch (error) {
          if (axios.isAxiosError(error)) {
            setError(error.response?.data as AxiosError)
          }
        }
      }
      fetchConfirmationData()
    }, [
      pEventId,
      hash,
      onGetConfirmationDataError,
      onGetConfirmationDataSuccess,
      isLoggedIn,
      skipInitialValidation,
    ])

    const onClose = () => {
      setShowCopyModal(false)
    }

    const updateShareActionData = async () => {
      if (hash) {
        const shareOptionsData = await getPreRegistrationShareOptions({
          hash,
        })
        setShareOptions(shareOptionsData.data)
        setShareActionData({
          shareActionToken: shareOptionsData.data.attributes.shareActionToken,
          tokenShuffleMethod: shareOptionsData.data.attributes.tokenShuffleMethod,
        })
      }
    }
    return (
      <ThemeProvider theme={themeMui}>
        {isLoggedIn && _isEmpaty(error) ? (
          <div className={`${classNamePrefix}_pre_registration_complete_container`}>
            <CopyMessageModal showCopyModal={showCopyModal} onClose={onClose} />
            <h2 className={`${classNamePrefix}_pre_registration_complete_header preregistration_confirmation_header`}>
              {pageHeader}
            </h2>
            <div className={`${classNamePrefix}_pre_registration_complete_message`}>
              {pageMessage}
            </div>
            <div className={`${classNamePrefix}_pre_registration_complete_body`}>
              {!_isEmpaty(prizes) && (
                <Prewards classNamePrefix={classNamePrefix} data={prizes} />
              )}

              {!_isEmpaty(shareOptions) && (
                <ShareOptions
                  classNamePrefix={classNamePrefix}
                  data={shareOptions}
                  onLinkCopied={() => {
                    setShowCopyModal(true)
                    onLinkCopied()
                  }}
                  shareActionData={shareActionData}
                  updateShareActionData={updateShareActionData}
                  hasCopyIcon={hasCopyIcon}
                  hash={hash}
                />
              )}
            </div>
          </div>
        ) : (
          showModalLogin && (
            <LoginModal
              logo={logo}
              onClose={() => {
                setShowModalLogin(false)
              }}
              onLogin={res => {
                setShowModalLogin(false)
                onLoginSuccess(res)
              }}
              showForgotPasswordButton
            />
          )
        )}
        {!_isEmpaty(error) && (
          <ConfirmModal
            hideCancelBtn
            message={error.message}
            onConfirm={() => onGetConfirmationDataError(error)}
          />
        )}
      </ThemeProvider>
    )
  }
