import { AxiosError } from 'axios'
import _get from 'lodash/get'
import React, { useEffect, useState } from 'react'

import { declineInvitation, processTicket } from '../../api'

export interface ITicketResaleContainer {
  onProcessTicketSuccess: (res: any) => void;
  onProcessTicketError: (e: AxiosError) => void;
  onDeclineTicketPurchaseSuccess: (res: any) => void;
  onDeclineTicketPurchaseError: (e: AxiosError) => void;
  orderHash?: string;
  billingPath?: string;
  defaultRedirection?: boolean;
}

export const TicketResaleContainer = ({
  onProcessTicketSuccess = () => {},
  onProcessTicketError = () => {},
  onDeclineTicketPurchaseSuccess = () => {},
  onDeclineTicketPurchaseError = () => {},
  orderHash,
  billingPath,
  defaultRedirection = true,
}: ITicketResaleContainer) => {
  const isWindowDefined = typeof window !== 'undefined'
  const [error, setError] = useState('')
  const [successMessage, setSuccessMessage] = useState('')

  useEffect(() => {
    (async () => {
      if (isWindowDefined) {
        const params: URLSearchParams = new URL(`${window.location}`).searchParams
        const hash = params.get('invitation_hash') || orderHash || null
        const isDeclined = params.get('decline') || false
        window.localStorage.removeItem('checkoutAdditionalConfigs')

        if (hash) {
          // Process of declining ticket purchase invitation
          if (isDeclined) {
            try {
              const response = await declineInvitation(hash)
              onDeclineTicketPurchaseSuccess(response)
              setSuccessMessage(
                "Thanks for letting us know! We'll offer this ticket to someone else!"
              )
            } catch (error) {
              setError(error?.response?.data?.message)
              onDeclineTicketPurchaseError(error.response)
            }
            return
          }

          try {
            const response = await processTicket(hash)
            const event_id = _get(response.data.data.attributes, 'event_id')
            const eventHasAddons = _get(response.data.data.attributes, 'has_add_on')
            const invitationIncludesAddons = _get(response.data.data.attributes, 'include_add_on')
            window.localStorage.setItem('checkoutAdditionalConfigs', JSON.stringify({
              resale: true,
              resaleWithAddons: eventHasAddons && invitationIncludesAddons,
            }))

            onProcessTicketSuccess(response.data)
            if (defaultRedirection) {
              window.location.href = `${billingPath ?? '/billing/billing-info'}?event_id=${event_id}`
            }
          } catch (error) {
            setError(error?.response?.data?.message)
            onProcessTicketError(error.response)
          }
        } else {
          window.location.href = '/'
        }
      }
    })()
  }, [])

  return (
    <div className="ticket-resale-page">
      <div className={`${successMessage ? 'success-block' : 'error-block'}`}>
        <h3>{successMessage ? successMessage : error}</h3>
      </div>
    </div>
  )
}
