import React, { useEffect } from 'react';
import { useBillingContext } from "@/billing-ui/context/BillingContext";
import LoadingSpinner from '@/billing-ui/components/ui/LoadingSpinner';
import dynamic from 'next/dynamic';
import useCreateSubscription from "@/billing-ui/hooks/useCreateSubscription";
import useSubscription from "@/billing-ui/hooks/useSubscription";
const BillingModal = dynamic(() => import('@/billing-ui/components/modals/BillingModal'), {
loading: () => <LoadingSpinner />,
});
const SuccessModal = dynamic(() => import('@/billing-ui/components/modals/SuccessModal'), {
loading: () => <LoadingSpinner />,
});
const ContactModal = dynamic(() => import('@/billing-ui/components/modals/ContactModal'), {
loading: () => <LoadingSpinner />,
});
const UpgradeModal = dynamic(() => import('@/billing-ui/components/modals/UpgradeModal'), {
loading: () => <LoadingSpinner />,
});
const EntitlementUsageLimitModal = dynamic(() => import('@/billing-ui/components/modals/EntitlementUsageLimitModal'), {
loading: () => <LoadingSpinner />,
});
const BillingLayout: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const {
isBillingModalOpen,
showSuccessModal,
showContactModal,
showUpgradeModal,
setIsBillingModalOpen,
setShowWelcomeModal,
setShowUpgradeModal,
handleSelectPlan,
handleContactUs,
handleSubmitContactUsForm,
closeSuccessModal,
closeContactModal,
closeBillingModal,
handleUpgrade,
handleSuccess,
userToken,
showEntitlementUsageLimitModal,
} = useBillingContext();
const { subscription, loading: subscriptionLoading } = useSubscription(String(userToken)) as any;
const { createSubscription, error } = useCreateSubscription(userToken);
useEffect(() => {
if (subscription && !subscription.isActive) {
setIsBillingModalOpen(true);
} else if (subscription && subscription?.isActive) {
setIsBillingModalOpen(false);
}
console.log(subscription)
}, [subscription]);
useEffect(() => {
if (localStorage.paymentSuccess && subscription) {
setIsBillingModalOpen(false);
handleSuccess(subscription);
localStorage.removeItem('paymentSuccess');
}
}, [localStorage, subscription]);
const handleTrial = async (planCode: string) => {
await createSubscription({
planCode,
isTrial: true,
});
if (!error) {
setShowWelcomeModal(true);
setIsBillingModalOpen(false);
setShowUpgradeModal(false);
}
};
return (
<>
{children}
{showEntitlementUsageLimitModal && (
<EntitlementUsageLimitModal />
)}
{isBillingModalOpen && (
<BillingModal
onSelectPlan={handleSelectPlan}
onContactUs={handleContactUs}
onTrial={handleTrial}
onClose={closeBillingModal}
/>
)}
{showSuccessModal && (
<SuccessModal onClose={closeSuccessModal} />
)}
{showContactModal && (
<ContactModal onSubmit={handleSubmitContactUsForm} onClose={closeContactModal} />
)}
{showUpgradeModal && (
<UpgradeModal handleTrial={handleTrial} handleUpgrade={handleUpgrade} />
)}
</>
);
};
export default BillingLayout;