/* eslint-disable max-len */
import './style.css'

import { Button } from '@mui/material'
import axios, { AxiosError } from 'axios'
import _get from 'lodash/get'
import _identity from 'lodash/identity'
import _map from 'lodash/map'
import React, { SyntheticEvent, useEffect, useRef, useState } from 'react'

import { getConfirmationData } from '../../api'
import { usePixel } from '../../hooks/usePixel'
import { IReferralPromotion } from '../../types'
import { createMarkup, getCookieByName, isBrowser } from '../../utils'
import { CopyMessageModal } from '../common'
import SocialButtons from './social-buttons'

export interface IShareButton {
  mainLabel: string;
  subLabel: string;
  platform: string;
  shareData: any;
  points?: number | string;
  onAfterShare?: (event: SyntheticEvent) => void;
  eventActionId?: string;
  oneTimeAction?: boolean;
  alreadyApplied?: boolean;
  btnClassName?: string;
}

export interface IConfirmationLabels {
  confirmationTitle?: string;
  confirmationMain?: string;
  confirmationHelper?: string;
  paymentPlanConfirmationTitle?: string;
  paymentPlanConfirmationMain?: string;
  paymentPlanConfirmationHelper?: string;
}

export interface IConfirmationPage {
  hasCopyIcon?: boolean;
  isReferralEnabled: boolean;
  showDefaultShareButtons: boolean;
  messengerAppId: string;
  shareButtons: IShareButton[];
  onGetConfirmationDataSuccess: (res: ICheckoutCompleteData) => void;
  onGetConfirmationDataError: (e: AxiosError) => void;
  onLinkCopied: () => void;
  orderHash?: string;
  confirmationLabels: IConfirmationLabels;
  clientLabel?: string;
  showReferralsInfoText?: boolean;
  showCopyInfoModal?: boolean;
  showPricingNoteSection?: boolean;
  showOrderDetailsBtn?: boolean;
  onOrderDetailsClick?: (data: ICheckoutCompleteData) => void;
  showProductImage?: boolean;
  eventTitle?: string;
  eventDate?: string;
  eventLocation?: string;
}

export const ConfirmationContainer = ({
  confirmationLabels,
  hasCopyIcon = true,
  isReferralEnabled,
  showDefaultShareButtons,
  messengerAppId = '',
  shareButtons = [],
  onGetConfirmationDataSuccess = _identity,
  onGetConfirmationDataError = _identity,
  orderHash,
  onLinkCopied = _identity,
  clientLabel,
  showReferralsInfoText = false,
  showCopyInfoModal = false,
  showPricingNoteSection = false,
  showOrderDetailsBtn = false,
  onOrderDetailsClick = _identity,
  showProductImage = true,
  eventTitle,
  eventDate,
  eventLocation,
}: IConfirmationPage) => {
  const inputRef = useRef(null)
  const [data, setData] = useState<ICheckoutCompleteData | null>(null)
  const dataEncoded = (isBrowser && window.localStorage.getItem('checkoutData')) || ''
  const dataDecoded = dataEncoded ? JSON.parse(dataEncoded) : { hash: orderHash }
  const { hash } = dataDecoded
  const eventId = data?.product_id || ''

  useEffect(() => {
    (async () => {
      if (hash) {
        try {
          const confirmationDataResponse = await getConfirmationData(hash)
          const data = confirmationDataResponse.data.attributes
          data.personal_share_sales = data.personal_share_sales.map(salesItem => {
            const salesData: IReferralPromotion = {
              label: `If your friends buy ${salesItem.sales} tickets`,
              price: '',
            }
            if (salesItem.price === 0) {
              salesData.subLabel = 'Your ticket becomes'
              salesData.price = 'FREE!'
            } else {
              salesData.subLabel = 'Your ticket goes down to'
              salesData.price = data.currency.symbol + Number(salesItem.price).toFixed(2)
            }

            return salesData
          })
          data.personal_share_sales.unshift({
            label: 'Your ticket is currently',
            price: data.currency.symbol + data.product_price?.toFixed(2),
          })
          // Ensure order_hash is included in the data
          if (!data.order_hash) {
            data.order_hash = hash
          }
          setData(data)
          onGetConfirmationDataSuccess(confirmationDataResponse.data.attributes)

          // Clear user_data for non-logged-in users after successful purchase
          if (isBrowser) {
            const isLoggedIn = Boolean(getCookieByName('X-TF-ECOMMERCE'))
            if (!isLoggedIn) {
              window.localStorage.removeItem('user_data')
            }
          }
        } catch (error) {
          if (axios.isAxiosError(error)) onGetConfirmationDataError(error)
        }
      }
    })()
  }, [hash])

  const [showCopyModal, setShowCopyModal] = useState(false)

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

  const onChangeShareLink = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newData = {
      ...data,
      personal_share_link: e.target.value,
    } as ICheckoutCompleteData
    setData(newData)
  }
  const {
    confirmationTitle = 'Your Tickets are Confirmed!',
    confirmationMain = 'Your tickets are available in My Tickets section',
    confirmationHelper = 'Please bring them with you to the event',
    paymentPlanConfirmationTitle = 'Your Tickets are Confirmed!',
    paymentPlanConfirmationMain = 'Your payment plan is pending and we are trying to take your initial payment. If your initial payment does not complete, your payment plan will be cancelled.',
    paymentPlanConfirmationHelper = 'You will receive a confirmation with your tickets once your final payment has been made.',
  } = confirmationLabels

  const pageUrl = isBrowser ? window.location.href.split('?')[0] : ''
  usePixel(eventId, { page: 'complete', pageUrl, orderHash: hash })

  return (
    <div className="confirmation-page">
      {showCopyInfoModal && (
        <CopyMessageModal onClose={onClose} showCopyModal={showCopyModal} />
      )}
      {data && (
        <>
          <div className="header-container">
            {showProductImage && (
              <div className="header-product-image">
                <img alt="" className="product-image" src={data.product_image} />
              </div>
            )}
            <div className="header-product-text">
              <p className="title">
                {data.is_payment_plan ? paymentPlanConfirmationTitle : confirmationTitle}
              </p>
              {(eventTitle || eventDate || eventLocation) && (
                <div className="event-details">
                  {eventTitle && <div className="event-title">{eventTitle}</div>}
                  {eventDate && <div className="event-date">{eventDate}</div>}
                  {eventLocation && <div className="event-location">{eventLocation}</div>}
                </div>
              )}
              <div
                className="share-message-section"
                dangerouslySetInnerHTML={
                  data.custom_confirmation_page_text &&
                  data.custom_confirmation_page_text_full_replacement
                    ? createMarkup(data.custom_confirmation_page_text)
                    : undefined
                }
              >
                {data.custom_confirmation_page_text &&
                data.custom_confirmation_page_text_full_replacement ? undefined : (
                  <>
                    {Boolean(data.is_payment_plan) && (
                      <>
                        <span className="main">{paymentPlanConfirmationMain}</span>
                        <span className="helper">{paymentPlanConfirmationHelper}</span>
                      </>
                    )}
                    {!data.is_payment_plan && (
                      <>
                        {data.attach_tickets ? (
                          <span className="main">
                            Your tickets have been emailed to you
                          </span>
                        ) : (
                          <span className="main">{confirmationMain}</span>
                        )}
                        <span className="helper">
                          {data.attach_tickets
                            ? 'Please bring them with you to the event'
                            : confirmationHelper}
                        </span>
                      </>
                    )}
                  </>
                )}
              </div>
            </div>
          </div>
          {data.custom_confirmation_page_text &&
          !data.custom_confirmation_page_text_full_replacement ? (
            <div
              className="custom-confirmation-page-text"
              dangerouslySetInnerHTML={createMarkup(data.custom_confirmation_page_text)}
            />
          ) : null}
          {showOrderDetailsBtn && (
            <div className="order-details-button-container">
              <Button
                className="view-order-button"
                variant="contained"
                onClick={() => {
                  onOrderDetailsClick(data)
                }}
              >
                View Order
              </Button>
            </div>
          )}
          {data.disable_referral === false && isReferralEnabled && (
            <>
              <div className="referral_text_image_section">
                <div className="referral_text_section">
                  <div className="referral_title_text">
                    Your ticket can become
                    <span className="strong-text"> cheaper </span>
                    or even
                    <span className="strong-text"> FREE!</span>
                  </div>
                  <div className="referral_text">
                    <span className="strong-text"> Invite friends </span>
                    and we'll refund up to
                    <span className="strong-text"> 100% </span>
                    of your ticket money, if they buy tickets as well!
                  </div>
                </div>
                <img
                  className="body-product-image"
                  src={data.product_image}
                  alt="No Data"
                />
              </div>
              <div className="share_wrapper">
                <div className="share_section">
                  <div className="invitation_section">
                    <div className="invitation_title">
                      How do you invite your friends?
                    </div>
                    <div className="share_buttons">
                      <div className="share-by-link">
                        <h5 className="share-by-link label">Send them this link:</h5>
                        <div className="share-btn-inner">
                          <input
                            ref={inputRef}
                            className="share-input"
                            value={data.personal_share_link}
                            onChange={onChangeShareLink}
                          />
                          <div
                            aria-hidden={true}
                            className="share-by-link-copy-icon"
                            onClick={() => {
                              navigator.clipboard.writeText(
                                _get(inputRef, 'current.value') || ''
                              )
                              setShowCopyModal(true)
                              onLinkCopied()
                            }}
                          >
                            {hasCopyIcon ? (
                              <img
                                src="https://img.icons8.com/office/50/000000/copy.png"
                                alt="copy"
                              />
                            ) : (
                              <span className="copy-icon">Copy</span>
                            )}
                          </div>
                        </div>
                      </div>
                      {(showDefaultShareButtons || !!shareButtons.length) && (
                        <SocialButtons
                          showDefaultShareButtons={showDefaultShareButtons}
                          name={data.product_name}
                          appId={messengerAppId}
                          shareLink={data.personal_share_link}
                          shareButtons={shareButtons}
                          clientLabel={clientLabel}
                          showReferralsInfoText={showReferralsInfoText}
                        />
                      )}
                    </div>
                  </div>
                </div>
                <div className="pricing-section">
                  <div className="invitation_title">How much cheaper?</div>
                  {_map(data.personal_share_sales, (pricing, index) => (
                    <div key={index} className="pricing-section_wrapper">
                      <div className="pricing-section_label">
                        {pricing.label}
                        {pricing.subLabel && (
                          <div className="pricing-section_sublabel">
                            {pricing.subLabel}
                          </div>
                        )}
                      </div>
                      <div className="pricing-section_price"> {pricing.price}</div>
                    </div>
                  ))}
                  {showPricingNoteSection && (
                    <div className="note-pricing-section">
                      ^ This is based on the most expensive ticket in your order.
                    </div>
                  )}
                </div>
              </div>
            </>
          )}
        </>
      )}
    </div>
  )
}
