'use client'
import React, { useEffect, useRef, useState } from 'react'
import { useSearchParams } from 'next/navigation'
import { useSelector, useDispatch } from 'react-redux'
import { asyncEventDetailsPayment } from '../../../../../../redux/Thunks/User/eventdetailspayment.thunk'
import { asyncBookEvent } from '../../../../../../redux/Thunks/User/bookevent.thunk'
import EventCardBox from './EventCardBox'
import CreditCard from './CreditCard'
import { sweetalert } from '@/app/components/common/Common'
import PaymentSideBar from './PaymentSideBar'
import AttendeesModal from '@/app/components/SiteModal/AttendeesModal/AttendeesModal'
import { useRouter } from 'next/navigation'
import SuccessModal from '@/app/components/SiteModal/SuccessModal/SuccessModal'
import PaymentErrorModal from '@/app/components/SiteModal/PaymentErrorModal/PaymentErrorModal'
import ErrorModal from '@/app/components/SiteModal/ErrorModal/ErrorModal'
import Paypal from './Paypal'
import Twint from './Twint'
import { getRedirectUrl } from '../../../../../utils/Redirect/redirect'
import TermsandConditionsModal from '@/app/components/SiteModal/TermsandConditionsModal/TermsandConditionsModal'
import {
    eventPaymentAdyanCreditCardThunk,
    eventPaymentStatusThunk,
    eventPaymentStripeThunk
} from '../../../../../../redux/Thunks/User/payment.adyan.thunk'
import { UserTermsAndConditionsViewThunk } from '../../../../../../redux/Thunks/User/TermsAndConditions/termsandconditions.thunk'
import AdyenCheckout from '@adyen/adyen-web'
import '@adyen/adyen-web/dist/adyen.css'
import H1 from '@/app/components/common/h1'
import Skeleton from '@/app/components/Skeleton/Skeleton'
import { useTranslation } from 'react-i18next'
import { getCookie, deleteCookie } from 'cookies-next'

import { loadStripe } from '@stripe/stripe-js'
import { Elements } from '@stripe/react-stripe-js'

import CheckoutForm from '../../../../components/CheckoutForm/CheckoutForm'
import requestApi from '@/utils/request'
import axios from 'axios'
import Swal from 'sweetalert2'

const stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY)

const PaymentModules = ({ category, languageName, organizerId, token, NEXT_CURRENT_WEB_DOMAIN }) => {
    const { i18n } = useTranslation()
    const dispatch = useDispatch()
    const paymentContainer = useRef(null)
    const router = useRouter()
    const { eventDetailsPayment, isLoading: detailLoader } = useSelector(
        (m) => m.eventdetailspayment
    )

    const [openTandC, setOpenTandC] = useState(false)
    const search = useSearchParams()
    const eId = search.get('eId')
    // const cId = search.get("cId")
    const quantityForBook = search.get('qty') || 1
    const redirectResult = search.get('redirectResult')
    const asAGift = search.get('gt')
    const showUserProfileInData = search.get('atd')
    const [loading, setLoading] = useState(false)
    const [status, setStatus] = useState(null)
    const [clientSecret, setClientSecret] = useState(null)
    const [applyKarmaPoints, setApplyKarmaPoints] = useState(false);
    const [stripeOptions, setStripeOptions] = useState(null)
    const EventData = eventDetailsPayment?.data?.eventData
    const EventPrice = eventDetailsPayment?.data?.paymentDetails
    const FreeEvents = Math.ceil(
        Number(eventDetailsPayment?.data?.paymentDetails?.subTotal)
    )
    // const attendessModelCookie = getCookie("attendees")
    const attendessModelCookie =
        typeof window !== 'undefined' && localStorage.getItem('attendees')
    const { viewDataTandC } = useSelector((e) => e?.TermsandConditionsUserSlice)
    const { guestBookEvent } = useSelector((e) => e?.guestBookEvent)
    const { userData } = useSelector((m) => m.authentication);
    const [paymentIntentData, setPaymentIntentData] = useState(null)
    const [patmentSessionStoreData, setPaymentSessionStoreData] = useState(null)
    // console.log('patmentSessionStoreData', patmentSessionStoreData)

    const prevKarmaPointsRef = useRef(null);

    // console.log('clientSecret', clientSecret)

    const errorIcon = `<svg class="svg-icon" version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 130.2 130.2">
                        <circle class="path circle" fill="none" stroke="#F96E66" stroke-width="6" stroke-miterlimit="10" cx="65.1" cy="65.1" r="62.1" />
                        <line class="path line" fill="none" stroke="#F96E66" stroke-width="6" stroke-linecap="round" stroke-miterlimit="10" x1="34.4" y1="37.9" x2="95.8" y2="92.3" />
                        <line class="path line" fill="none" stroke="#F96E66" stroke-width="6" stroke-linecap="round" stroke-miterlimit="10" x1="95.8" y1="38" x2="34.4" y2="92.2" />
                    </svg>`

    const CancelModal = () => {
        setshow(false)
        // setShowAttendeesModal(true)
        router.push(`/e-ticket?tId=${EventData?.eventId}&cId=${category}`)
        document.body.classList.remove('open-modal')
    }

    // useEffect(() => {
    //     if (clientSecret) {
    //         setClientSecret(null)
    //     }
    // }, [applyKarmaPoints])

    useEffect(() => {
        dispatch(
            asyncEventDetailsPayment({
                eventId: eId,
                quantity: quantityForBook,
                applyKarmaPoint: applyKarmaPoints
            })
        )
    }, [applyKarmaPoints])

    useEffect(() => {
        if (organizerId) {
            dispatch(UserTermsAndConditionsViewThunk({ userId: organizerId }))
        }

    }, [organizerId])

    const closeTandCmodal = () => {
        setOpenTandC(false)
        document.body.classList.remove('open-modal')
    }
    const handleTandCmodalopen = () => {
        setOpenTandC(true)
        document.body.classList.add('open-modal')
    }

    useEffect(() => {
        // Ensure necessary values are available before making the request
        if (!eId || !quantityForBook || !languageName || !eventDetailsPayment) {
            return; // Avoid triggering side effects if data is missing
        }

        if (applyKarmaPoints !== prevKarmaPointsRef.current) {
            if (!!FreeEvents) {
                let obj = {}
                setClientSecret(null)
                obj.eventId = eId,
                    obj.languageName = languageName,
                    obj.quantity = quantityForBook
                obj.applyKarmaPoint = applyKarmaPoints
                if (asAGift !== 'null') {
                    obj.asAGift = JSON.parse(asAGift)
                }
                // obj.returnUrl = `${process.env.NEXT_PUBLIC_BASE_URL_REDIRECTION}/status/?id=${eId}&cId=${category}`
                obj.returnUrl = `${NEXT_CURRENT_WEB_DOMAIN}/${eventDetailsPayment?.data?.eventData?.categorySlug}/${eventDetailsPayment?.data?.eventData?.slug}`
                if (patmentSessionStoreData) {
                    obj.orderRef = patmentSessionStoreData?.orderRef
                }
                // obj.showUserProfileInData = showUserProfileInData === "true" ? true : false
                // dispatch(eventPaymentAdyanCreditCardThunk(obj));

                // dispatch(eventPaymentStripeThunk(obj));

                if (userData) {
                    requestApi
                        .post('/endUser/events/create-payment-intent', obj)
                        .then((res) => {
                            setPaymentIntentData(res?.data)
                            setClientSecret(res?.data?.clientSecret)
                            setStripeOptions({
                                clientSecret: res?.data?.clientSecret,
                                appearance,
                                locale: languageName ? languageName : "en"
                            })
                        }
                        )
                        .catch((error) => {
                            // console.log('Error', error);
                            Swal.fire({
                                html: `<div class='custom-swal-modal'>
                                        <div class='modal-body'>
                                            ${errorIcon}
                                            <h2>${error?.message}</h2>
                                        </div>
                                    </div>`,
                                allowOutsideClick: false,
                                confirmButtonText: 'Try Again',
                            }).then(() => {
                                // When the user clicks "Try Again", redirect them
                                router.push(
                                    `/${eventDetailsPayment?.data?.eventData?.categorySlug}/${eventDetailsPayment?.data?.eventData?.slug}`
                                );
                                return true;
                            });
                            setClientSecret(null);
                        });
                } else {
                    if (guestBookEvent) {
                        // console.log('guestBookEvent', guestBookEvent)
                        obj.userId = guestBookEvent?.userId
                        obj.firstName = guestBookEvent?.firstName
                        obj.lastName = guestBookEvent?.lastName
                        obj.email = guestBookEvent?.email
                        obj.isGuestBooking = true
                        obj.returnUrl = `${NEXT_CURRENT_WEB_DOMAIN}`
                        if (patmentSessionStoreData) {
                            obj.orderRef = patmentSessionStoreData?.orderRef
                        }
                        // obj.returnUrl = 'http://localhost:3000'
                        requestApi
                            .post('/endUser/events/guest/create-payment-intent', obj)
                            .then((res) => {
                                setPaymentIntentData(res?.data)
                                setClientSecret(res?.data?.clientSecret)
                                setStripeOptions({
                                    clientSecret: res?.data?.clientSecret,
                                    appearance,
                                    locale: languageName ? languageName : "en"
                                })
                            }
                            ).catch((error) => {
                                Swal.fire({
                                    html: `<div class='custom-swal-modal'>
                                            <div class='modal-body'>
                                                ${errorIcon}
                                                <h2>${error?.message}</h2>
                                            </div>
                                        </div>`,
                                    allowOutsideClick: false,
                                    confirmButtonText: 'Try Again',
                                }).then(() => {
                                    // When the user clicks "Try Again", redirect them
                                    router.push(
                                        `/${eventDetailsPayment?.data?.eventData?.categorySlug}/${eventDetailsPayment?.data?.eventData?.slug}`
                                    );
                                    return true;
                                });
                                setClientSecret(null);
                            });
                    } else {
                        if (eventDetailsPayment) {
                            router.push(
                                `/${eventDetailsPayment?.data?.eventData?.categorySlug}/${eventDetailsPayment?.data?.eventData?.slug}`
                            );
                        } else {
                            router.back()
                        }
                    }
                }

            }
            prevKarmaPointsRef.current = applyKarmaPoints;
        }
        // if (!attendessModelCookie) {
        //   setShowAttendeesModal(true);
        // }
    }, [FreeEvents, applyKarmaPoints, paymentIntentData, clientSecret, eId, quantityForBook, asAGift, languageName, userData, guestBookEvent, category, eventDetailsPayment?.data?.eventData?.categorySlug, eventDetailsPayment?.data?.eventData?.slug])

    const appearance = {
        theme: 'stripe'
    }
    const options = {
        clientSecret,
        appearance,
        locale: languageName ? languageName : "en"
    }
    useEffect(() => {
        setStripeOptions({
            clientSecret,
            appearance,
            locale: languageName ? languageName : "en"
        })
    }, [])

    useEffect(() => {
        if (!userData && !guestBookEvent) {
            router.back()
        }
        return () => {
            sessionStorage.removeItem('orderRef')
        }
    }, [])

    // // Function to handle the beforeunload event and trigger Swal modal
    // const handleBeforeUnload = (event) => {
    //     // Only trigger SweetAlert if the user has unsaved changes or some condition
    //     Swal.fire({
    //         title: 'Are you sure?',
    //         text: "You may lose your unsaved changes!",
    //         icon: 'warning',
    //         showCancelButton: true,
    //         confirmButtonText: 'Leave',
    //         cancelButtonText: 'Stay',
    //     }).then((result) => {
    //         if (!result.isConfirmed) {
    //             event.preventDefault();  // If the user cancels, prevent unload
    //         }
    //     });

    //     // This prevents the default browser dialog and triggers SweetAlert2
    //     event.returnValue = ''; // Required for some browsers
    // };

    // // Adding event listener on mount and cleaning it up on unmount
    // useEffect(() => {
    //     window.addEventListener('beforeunload', handleBeforeUnload);

    //     // Cleanup on component unmount
    //     return () => {
    //         window.removeEventListener('beforeunload', handleBeforeUnload);
    //     };
    // }, []);

    useEffect(() => {
        if (typeof window !== 'undefined') {
            const orderRefff = sessionStorage.getItem('orderRef') || null
            if (orderRefff !== "undefined") {
                let obj = {
                    orderRef: orderRefff
                }
                // console.log(obj, 'obj')
                setPaymentSessionStoreData(obj)
            }
            sessionStorage.setItem('orderRef', paymentIntentData?.orderRef)
        }

    }, [paymentIntentData, applyKarmaPoints])

    return (
        <>
            <div className="flex items-stretch justify-between flex-col md:flex-row web-setting-wrapper">
                <div className="web-setting-content payment-setting-content">
                    <div className="flex items-center card-details ">
                        <>
                            <div className='w-full lg:w-1/2 3xl:w-3/5 payment-card-body'>
                                <p className="policy-title">{i18n.t(`payment.paymentrefundline`)} <span className="link"
                                    onClick={() => handleTandCmodalopen()}
                                >{i18n.t(`payment.paymentrefundline1`)}</span> {i18n.t(`payment.paymentrefundline2`)}</p>
                                {/* <h1 className="title">{i18n.t(`payment.title`)}</h1> */}
                                <div className='payment-form-wrapper'>
                                    {clientSecret && (
                                        <Elements
                                            options={stripeOptions}
                                            stripe={stripePromise}
                                        >
                                            <CheckoutForm paymentIntentData={paymentIntentData} tId={EventData?.eventId} cId={category} eventDetails={eventDetailsPayment} setApplyKarmaPoints={setApplyKarmaPoints} applyKarmaPoints={applyKarmaPoints} />
                                        </Elements>
                                    )}
                                </div>
                            </div>
                            <div
                                className={`w-full ${!FreeEvents
                                    ? 'freecard   '
                                    : 'lg:w-1/2 3xl:w-2/5'
                                    }`}
                            >
                                <EventCardBox
                                    eventData={eventDetailsPayment?.data}
                                    languageName={languageName}
                                    token={token}
                                />
                            </div>
                        </>
                    </div>
                </div>
            </div>

            {openTandC && (
                <TermsandConditionsModal
                    show={openTandC}
                    title={i18n.t(`organizer.termsandconditions.heading`)}
                    description={viewDataTandC?.termsAndConditions}
                    CancelModal={() => closeTandCmodal()}
                    cancelBtn={i18n.t(`settings.deleteModal.cancleBtn`)}
                />
            )}

            {/* <SuccessModal
                      show={show}
                      title={i18n.t(`payment.model.SuccessModal.title`)}
                      description={i18n.t(
                          `payment.model.SuccessModal.description`
                      )}
                      SolidBTNText={i18n.t(
                          `payment.model.SuccessModal.SolidBTNText`
                      )}
                      CancelModal={() => {
                          CancelModal()
                      }}
                  /> */}
            {/* {!!FreeEvents && showAttendeesModal && (
            <AttendeesModal
              show={showAttendeesModal}
              setshow={setShowAttendeesModal}
              title={i18n.t(`payment.model.AttendeesModal.title`)}
              onClickCancleText={i18n.t(
                `payment.model.AttendeesModal.onClickCancleText`
              )}
              SolidBTNText={i18n.t(`payment.model.AttendeesModal.SolidBTNText`)}
              onClickCancle={
                () => {
                  router.push(
                    `/events/payment/?eId=${eId}&cId=${category}&qty=${quantityForBook}&gt=${asAGift}&atd=false`
                  );
                  setShowAttendeesModal(false);
                  // document.cookie = 'attendees="false";'
                  localStorage.setItem("attendees", "false");
                }
                // AttendeesName(
                //   i18n.t(`payment.model.AttendeesModal.onClickCancleText`)
                // )
              }
              onClickOK={
                () => {
                  router.push(
                    `/events/payment/?eId=${eId}&cId=${category}&qty=${quantityForBook}&gt=${asAGift}&atd=true`
                  );
                  setShowAttendeesModal(false);
                  // document.cookie = 'attendees="true";'
                  localStorage.setItem("attendees", "true");
                }
                // AttendeesName(
                //   i18n.t(`payment.model.AttendeesModal.SolidBTNText`)
                // )
              }
            />
          )} */}
            {/* {paymentError && (
                      <PaymentErrorModal
                          show={paymentError}
                          title={
                              errorMessage
                                  ? errorMessage
                                  : i18n.t(
                                        `payment.model.PaymentErrorModal.title`
                                    )
                          }
                          // description={i18n.t(
                          //   `payment.model.PaymentErrorModal.description`
                          // )}
                          SolidBTNText={i18n.t(
                              `payment.model.PaymentErrorModal.SolidBTNText`
                          )}
                          CancelModal={() => {
                              window.location.reload()
                              setPaymentError(false)
                              setErrorMessage(null)
                          }}
                      />
                  )} */}
            {/* {bookedEvent && (
                      <ErrorModal
                          show={bookedEvent}
                          setshow={setshow}
                          url={'/events/'}
                          description={bookedErrormessage}
                          //  CancelModal = {()=>{
                          //      setshow(false)
                          //      router.push('/events/')
                          //     }}
                      />
                  )} */}
        </>
    )
}

export default PaymentModules
