import React, { createContext, useState, useEffect, useMemo } from 'react';
import { Facebook, Messenger, Linkedin, TwitterX, Gmail, Line, Outlook, WeChat, WhatsApp, Telegram, Skype, Trello } from '../../icons';
import axios from 'axios';
import CustomOption from '../components/CustomOption';
import CouponTypeProOption from '../components/CouponTypeProOption';
import SubscriptionProOption from '../components/SubscriptionProOption';

const SettingsContext = createContext();
const default_settings = ecreAdmin.default_settings;

const SettingsProvider = ({ children }) => {
    const getLocalizedPageLabel = (label) => {
        switch (label) {
            case 'Home': return ecreAdmin.strings.page_name_home;
            case 'Shop': return ecreAdmin.strings.page_name_shop;
            case 'Cart': return ecreAdmin.strings.page_name_cart;
            case 'My account': return ecreAdmin.strings.page_name_my_account;
            case 'Checkout': return ecreAdmin.strings.page_name_checkout;
            default: return label;
        }
    };

    const [activeTab, setActiveTab] = useState(localStorage.getItem('active-tab') || 'referral_settings');
    const [ecreActiveScreen, setEcreActiveScreen] = useState(() => {
    const savedScreen = localStorage.getItem('ecre-active-screen');
        return (savedScreen && savedScreen !== 'null') ? savedScreen : 'reward_management';
    });
    const [activeReferrerTab, setActiveReferrerTab] = useState(localStorage.getItem('ecre-referrer-tab') || 'referral-history');
    const [isCollapsed, setIsCollapsed] = useState(false);
    const [isVisible, setIsVisible] = useState(true);
    const [isOpen, setIsOpen] = useState(false);
    // const [isPro, setIsPro] = useState(true);
    const [isPro, setIsPro] = useState(ecreAdmin.is_pro);
    const [isReferralMailModal, setIsReferralMailModal] = useState(false);
    const [isReferralMailTagModal, setIsReferralMailTagModal] = useState(false);
    const [isRewardMailTagModal, setIsRewardMailTagModal] = useState(false);
    const [isRewardMailModal, setIsRewardMailModal] = useState(false);
    const [copiedItemIndex, setCopiedItemIndex] = useState(null);
    const [referralCoupon, setReferralCoupon] = useState({});
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(false);
    const [woocommerceProductOptions, setProducts] = useState([]);
    const [woocommerceProductCategoryOptions, setCategories] = useState([]);
    const [pagesOptions, setPagesOptions] = useState([]);

    const [selectedReferrer, setSelectedReferrer] = useState(() => {
        const saved = localStorage.getItem('ecre-selected-referrer');
        return saved ? JSON.parse(saved) : null;
    });

    const [referrerDetailsSummary, setReferrerDetailsSummary] = useState({
        conversion_rate: 0,
        total_referral_sales: 0,
        total_referrals: 0,
        reward_issued: 0
    });

    // Create a wrapper for setSelectedReferrer that also saves to localStorage
    const handleSetSelectedReferrer = (referrer) => {
        setSelectedReferrer(referrer);
        if (referrer) {
            localStorage.setItem('ecre-selected-referrer', JSON.stringify(referrer));
        } else {
            localStorage.removeItem('ecre-selected-referrer');
        }
    };

    
    const initialFormData = {
        enableReferralProgram: default_settings.hasOwnProperty('enableReferralProgram') ? default_settings.enableReferralProgram : false,
        enableReferralLink: default_settings.hasOwnProperty('enableReferralLink') ? default_settings.enableReferralLink : false,
        referralDiscount: default_settings.hasOwnProperty('referralDiscount') ? default_settings.referralDiscount :  0,
        noOrderMessageToReferrer: default_settings.hasOwnProperty('noOrderMessageToReferrer') ? default_settings.noOrderMessageToReferrer :  'Hello',
        referralSignupCouponNote: default_settings.hasOwnProperty('referralSignupCouponNote') ? default_settings.referralSignupCouponNote : 'This coupon can be applied for subscription sign up fee discount only',
        referralRecurringCouponNote: default_settings.hasOwnProperty('referralRecurringCouponNote') ? default_settings.referralRecurringCouponNote : 'This coupon can be applied for subscription renewal fee discount only',
        referralWidgetPosition: default_settings.hasOwnProperty('referralWidgetPosition') ? default_settings.referralWidgetPosition : 'left',
        referralDiscountCapping: default_settings.hasOwnProperty('referralDiscountCapping') ? default_settings.referralDiscountCapping : 0,
        referralMenuName: default_settings.hasOwnProperty('referralMenuName') ? default_settings.referralMenuName : 'EchoRewards Program',
        referralMonthlyLimit: default_settings.hasOwnProperty('referralMonthlyLimit') ? default_settings.referralMonthlyLimit : 0,
        referralMinimumPurchaseAmount: default_settings.hasOwnProperty('referralMinimumPurchaseAmount') ? default_settings.referralMinimumPurchaseAmount : 0,
        referralCouponPrefix: default_settings.hasOwnProperty(' referralCouponPrefix') ? default_settings. referralCouponPrefix : 'ECHO',
        canRefferOthers: default_settings.hasOwnProperty('canRefferOthers') ? default_settings.canRefferOthers : false,
        canUseReferralCoupon: default_settings.hasOwnProperty('canUseReferralCoupon') ? default_settings.canUseReferralCoupon : false,
        is_user_loggedin: default_settings.hasOwnProperty('is_user_loggedin') ? default_settings.is_user_loggedin : false,
        enableReferralLimit: default_settings.hasOwnProperty('enableReferralLimit') ? default_settings.enableReferralLimit : false,
        enableReferralLimitSubscriptionCoupon: default_settings.hasOwnProperty('enableReferralLimitSubscriptionCoupon') ? default_settings.enableReferralLimitSubscriptionCoupon : false,
        referralLimitSubscriptionCoupon: default_settings.hasOwnProperty('referralLimitSubscriptionCoupon') ? default_settings.referralLimitSubscriptionCoupon : 0,
        enableRewardLimitSubscriptionCoupon: default_settings.hasOwnProperty('enableRewardLimitSubscriptionCoupon') ? default_settings.enableRewardLimitSubscriptionCoupon : false,
        rewardLimitSubscriptionCoupon: default_settings.hasOwnProperty('rewardLimitSubscriptionCoupon') ? default_settings.rewardLimitSubscriptionCoupon : 0,
        enableTabOnWooCommerceProduct: default_settings.hasOwnProperty('enableTabOnWooCommerceProduct') ? default_settings.enableTabOnWooCommerceProduct : false,
        enableReferralFloatingWidget: default_settings.hasOwnProperty('enableReferralFloatingWidget') ? default_settings.enableReferralFloatingWidget : false,
        enableReferralSocialSharing: default_settings.hasOwnProperty('enableReferralSocialSharing') ? default_settings.enableReferralSocialSharing : false,
        hideReferralMenuIcon: default_settings.hasOwnProperty('hideReferralMenuIcon') ? default_settings.hideReferralMenuIcon : false,
        referralIncludeProducts: default_settings.hasOwnProperty('referralIncludeProducts') ? default_settings.referralIncludeProducts : [],
        referralExcludeProducts: default_settings.hasOwnProperty('referralExcludeProducts') ? default_settings.referralExcludeProducts : [],
        referralIncludeCategories: default_settings.hasOwnProperty('referralIncludeCategories') ? default_settings.referralIncludeCategories : [],
        referralExcludeCategories: default_settings.hasOwnProperty('referralExcludeCategories') ? default_settings.referralExcludeCategories : [],
        pagesForWidgets: (default_settings.hasOwnProperty('pagesForWidgets') ? default_settings.pagesForWidgets : []).map(page => ({ ...page, label: getLocalizedPageLabel(page.label) })),
        referralCouponType: default_settings.hasOwnProperty('referralCouponType') ? default_settings.referralCouponType : [],
        socialMediaOptions: default_settings.hasOwnProperty('socialMediaOptions') ? default_settings.socialMediaOptions : [],
        rewardType: default_settings.hasOwnProperty('rewardType') ? default_settings.rewardType : [],
        rewardPoint: default_settings.hasOwnProperty('rewardPoint') ? default_settings.rewardPoint : 0,
        rewardDiscount: default_settings.hasOwnProperty('rewardDiscount') ? default_settings.rewardDiscount : 0,
        redeemPoint: default_settings.hasOwnProperty('redeemPoint') ? default_settings.redeemPoint : 0,
        redeemDiscount: default_settings.hasOwnProperty('redeemDiscount') ? default_settings.redeemDiscount : 0,
        minimumRewardPointAmount: default_settings.hasOwnProperty('minimumRewardPointAmount') ? default_settings.minimumRewardPointAmount : 0,
        enableRedeemLimit: default_settings.hasOwnProperty('enableRedeemLimit') ? default_settings.enableRedeemLimit : true,
        enableRewardPointExpiry: default_settings.hasOwnProperty('enableRewardPointExpiry') ? default_settings.enableRewardPointExpiry : false,
        rewardPointExpiryAction: default_settings.hasOwnProperty('rewardPointExpiryAction') ? default_settings.rewardPointExpiryAction : 'unavailable',
        rewardOrderStatus: default_settings.hasOwnProperty('rewardOrderStatus') ? default_settings.rewardOrderStatus : { value: 'wc-completed', label: 'Completed' },
        rewardPointExpiry: default_settings.hasOwnProperty('rewardPointExpiry') ? default_settings.rewardPointExpiry : 0,
        redeemLimit: default_settings.hasOwnProperty('redeemLimit') ? default_settings.redeemLimit : 0,
        rewardDiscountCapping: default_settings.hasOwnProperty('rewardDiscountCapping') ? default_settings.rewardDiscountCapping : 0,
        rewardMinimumPurchaseAmount: default_settings.hasOwnProperty('rewardMinimumPurchaseAmount') ? default_settings.rewardMinimumPurchaseAmount : 0,
        enableRewardExpiry: default_settings.hasOwnProperty('enableRewardExpiry') ? default_settings.enableRewardExpiry : false,
        rewardCouponValidity: default_settings.hasOwnProperty('rewardCouponValidity') ? default_settings.rewardCouponValidity : 0,
        enableRewardCouponUsageLimit: default_settings.hasOwnProperty('enableRewardCouponUsageLimit') ? default_settings.enableRewardCouponUsageLimit : false,
        rewardCouponUsageLimit: default_settings.hasOwnProperty('rewardCouponUsageLimit') ? default_settings.rewardCouponUsageLimit : 0,
        enableRewardDelayTime: default_settings.hasOwnProperty('enableRewardDelayTime') ? default_settings.enableRewardDelayTime : false,
        rewardDelayTime: default_settings.hasOwnProperty('rewardDelayTime') ? default_settings.rewardDelayTime : 0,
        rewardIncludeProducts: default_settings.hasOwnProperty('rewardIncludeProducts') ? default_settings.rewardIncludeProducts : [],
        rewardExcludeProducts: default_settings.hasOwnProperty('rewardExcludeProducts') ? default_settings.rewardExcludeProducts : [],
        rewardIncludeCategories: default_settings.hasOwnProperty('rewardIncludeCategories') ? default_settings.rewardIncludeCategories : [],
        rewardExcludeCategories: default_settings.hasOwnProperty('rewardExcludeCategories') ? default_settings.rewardExcludeCategories : [],
        enableRefferalEmailInvitation: default_settings.hasOwnProperty('enableRefferalEmailInvitation') ? default_settings.enableRefferalEmailInvitation : false,
        referralEmailSubject: default_settings.hasOwnProperty('referralEmailSubject') ? default_settings.referralEmailSubject : '',
        referralEmailHeading: default_settings.hasOwnProperty('referralEmailHeading') ? default_settings.referralEmailHeading : '',
        referralEmailBody: default_settings.hasOwnProperty('referralEmailBody') ? default_settings.referralEmailBody : '',
        enableRewardEmailInvitation: default_settings.hasOwnProperty('enableRewardEmailInvitation') ? default_settings.enableRewardEmailInvitation : false,
        rewardEmailSubject: default_settings.hasOwnProperty('rewardEmailSubject') ? default_settings.rewardEmailSubject : '',
        rewardEmailHeading: default_settings.hasOwnProperty('rewardEmailHeading') ? default_settings.rewardEmailHeading : '',
        rewardEmailBody: default_settings.hasOwnProperty('rewardEmailBody') ? default_settings.rewardEmailBody : '',
        referralMenuIcon: default_settings.hasOwnProperty('referralMenuIcon') ? default_settings.referralMenuIcon : '',
    };

    
    const [formData, setFormData] = useState(initialFormData);
    const [lastSavedFormData, setLastSavedFormData] = useState(initialFormData);
    const [hasChanges, setHasChanges] = useState(false);

    const fetchData = async () => {
        try {
            setLoading(true);
            const formDataToSend = new FormData();
            formDataToSend.append('action', 'ecre_fetch_settings');
            formDataToSend.append('nonce', ecreAdmin.nonce);

            const response = await axios.post(ecreAdmin.ajaxurl, formDataToSend, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                },
            });

            if (response.data.success) {
                const fetchedData = response.data.data;

                if (fetchedData) {
                    const updatedFormData = {
                        // For each field, check if it exists in fetchedData
                        // If it's defined (even if false), use that value
                        // Otherwise fall back to initialFormData
                        enableReferralProgram: fetchedData.hasOwnProperty('enableReferralProgram') ? fetchedData.enableReferralProgram : initialFormData.enableReferralProgram,
                        enableReferralLink: fetchedData.hasOwnProperty('enableReferralLink') ? fetchedData.enableReferralLink : initialFormData.enableReferralLink,
                        referralDiscount: fetchedData.hasOwnProperty('referralDiscount') ? fetchedData.referralDiscount : initialFormData.referralDiscount,
                        discountCapping: fetchedData.hasOwnProperty('discountCapping') ? fetchedData.discountCapping : initialFormData.discountCapping,
                        noOrderMessageToReferrer: fetchedData.hasOwnProperty('noOrderMessageToReferrer') ? fetchedData.noOrderMessageToReferrer : initialFormData.noOrderMessageToReferrer,
                        referralSignupCouponNote: fetchedData.hasOwnProperty('referralSignupCouponNote') ? fetchedData.referralSignupCouponNote : initialFormData.referralSignupCouponNote,
                        referralRecurringCouponNote: fetchedData.hasOwnProperty('referralRecurringCouponNote') ? fetchedData.referralRecurringCouponNote : initialFormData.referralRecurringCouponNote,
                        referralWidgetPosition: fetchedData.hasOwnProperty('referralWidgetPosition') ? fetchedData.referralWidgetPosition : initialFormData.referralWidgetPosition,
                        referralDiscountCapping: fetchedData.hasOwnProperty('referralDiscountCapping') ? fetchedData.referralDiscountCapping : initialFormData.referralDiscountCapping,
                        referralMenuName: fetchedData.hasOwnProperty('referralMenuName') ? fetchedData.referralMenuName : initialFormData.referralMenuName,
                        referralMonthlyLimit: fetchedData.hasOwnProperty('referralMonthlyLimit') ? fetchedData.referralMonthlyLimit : initialFormData.referralMonthlyLimit,
                        referralMinimumPurchaseAmount: fetchedData.hasOwnProperty('referralMinimumPurchaseAmount') ? fetchedData.referralMinimumPurchaseAmount : initialFormData.referralMinimumPurchaseAmount,
                        referralCouponPrefix: fetchedData.hasOwnProperty('referralCouponPrefix') ? fetchedData.referralCouponPrefix : initialFormData.referralCouponPrefix,
                        canRefferOthers: fetchedData.hasOwnProperty('canRefferOthers') ? fetchedData.canRefferOthers : initialFormData.canRefferOthers,
                        canUseReferralCoupon: fetchedData.hasOwnProperty('canUseReferralCoupon') ? fetchedData.canUseReferralCoupon : initialFormData.canUseReferralCoupon,
                        is_user_loggedin: fetchedData.hasOwnProperty('is_user_loggedin') ? fetchedData.is_user_loggedin : initialFormData.is_user_loggedin,
                        enableReferralLimit: fetchedData.hasOwnProperty('enableReferralLimit') ? fetchedData.enableReferralLimit : initialFormData.enableReferralLimit,
                        enableReferralLimitSubscriptionCoupon: fetchedData.hasOwnProperty('enableReferralLimitSubscriptionCoupon') ? (isPro ? fetchedData.enableReferralLimitSubscriptionCoupon : false) : initialFormData.enableReferralLimitSubscriptionCoupon,
                        referralLimitSubscriptionCoupon: fetchedData.hasOwnProperty('referralLimitSubscriptionCoupon') ? fetchedData.referralLimitSubscriptionCoupon : initialFormData.referralLimitSubscriptionCoupon,
                        enableTabOnWooCommerceProduct: fetchedData.hasOwnProperty('enableTabOnWooCommerceProduct') ? fetchedData.enableTabOnWooCommerceProduct : initialFormData.enableTabOnWooCommerceProduct,
                        enableReferralFloatingWidget: fetchedData.hasOwnProperty('enableReferralFloatingWidget') ? fetchedData.enableReferralFloatingWidget : initialFormData.enableReferralFloatingWidget,
                        enableReferralSocialSharing: fetchedData.hasOwnProperty('enableReferralSocialSharing') ? fetchedData.enableReferralSocialSharing : initialFormData.enableReferralSocialSharing,
                        hideReferralMenuIcon: fetchedData.hasOwnProperty('hideReferralMenuIcon') ? fetchedData.hideReferralMenuIcon : initialFormData.hideReferralMenuIcon,
                        pagesForWidgets: (fetchedData.hasOwnProperty('pagesForWidgets') ? fetchedData.pagesForWidgets : initialFormData.pagesForWidgets).map(page => ({ ...page, label: getLocalizedPageLabel(page.label) })),
                        referralIncludeProducts: fetchedData.hasOwnProperty('referralIncludeProducts') ? fetchedData.referralIncludeProducts : initialFormData.referralIncludeProducts,
                        referralExcludeProducts: fetchedData.hasOwnProperty('referralExcludeProducts') ? fetchedData.referralExcludeProducts : initialFormData.referralExcludeProducts,
                        referralIncludeCategories: fetchedData.hasOwnProperty('referralIncludeCategories') ? fetchedData.referralIncludeCategories : initialFormData.referralIncludeCategories,
                        referralExcludeCategories: fetchedData.hasOwnProperty('referralExcludeCategories') ? fetchedData.referralExcludeCategories : initialFormData.referralExcludeCategories,
                        referralCouponType: fetchedData.hasOwnProperty('referralCouponType') ? fetchedData.referralCouponType : initialFormData.referralCouponType,
                        socialMediaOptions: fetchedData.hasOwnProperty('socialMediaOptions') ? fetchedData.socialMediaOptions : initialFormData.socialMediaOptions,
                        rewardType: fetchedData.hasOwnProperty('rewardType') ? fetchedData.rewardType : initialFormData.rewardType,
                        rewardPoint: fetchedData.hasOwnProperty('rewardPoint') ? fetchedData.rewardPoint : initialFormData.rewardPoint,
                        redeemPoint: fetchedData.hasOwnProperty('redeemPoint') ? fetchedData.redeemPoint : initialFormData.redeemPoint,
                        redeemLimit: fetchedData.hasOwnProperty('redeemLimit') ? fetchedData.redeemLimit : initialFormData.redeemLimit,
                        enableRedeemLimit: fetchedData.hasOwnProperty('enableRedeemLimit') ? fetchedData.enableRedeemLimit : initialFormData.enableRedeemLimit,
                        enableRewardPointExpiry: fetchedData.hasOwnProperty('enableRewardPointExpiry') ? fetchedData.enableRewardPointExpiry : initialFormData.enableRewardPointExpiry,
                        enableRewardLimitSubscriptionCoupon: fetchedData.hasOwnProperty('enableRewardLimitSubscriptionCoupon') ? fetchedData.enableRewardLimitSubscriptionCoupon : initialFormData.enableRewardLimitSubscriptionCoupon,
                        rewardLimitSubscriptionCoupon: fetchedData.hasOwnProperty('rewardLimitSubscriptionCoupon') ? fetchedData.rewardLimitSubscriptionCoupon : initialFormData.rewardLimitSubscriptionCoupon,
                        rewardPointExpiryAction: fetchedData.hasOwnProperty('rewardPointExpiryAction') ? fetchedData.rewardPointExpiryAction : initialFormData.rewardPointExpiryAction,
                        rewardPointExpiry: fetchedData.hasOwnProperty('rewardPointExpiry') ? fetchedData.rewardPointExpiry : initialFormData.rewardPointExpiry,
                        minimumRewardPointAmount: fetchedData.hasOwnProperty('minimumRewardPointAmount') ? fetchedData.minimumRewardPointAmount : initialFormData.minimumRewardPointAmount,
                        redeemDiscount: fetchedData.hasOwnProperty('redeemDiscount') ? fetchedData.redeemDiscount : initialFormData.redeemDiscount,
                        rewardDiscount: fetchedData.hasOwnProperty('rewardDiscount') ? fetchedData.rewardDiscount : initialFormData.rewardDiscount,
                        rewardDiscountCapping: fetchedData.hasOwnProperty('rewardDiscountCapping') ? fetchedData.rewardDiscountCapping : initialFormData.rewardDiscountCapping,
                        rewardMinimumPurchaseAmount: fetchedData.hasOwnProperty('rewardMinimumPurchaseAmount') ? fetchedData.rewardMinimumPurchaseAmount : initialFormData.rewardMinimumPurchaseAmount,
                        enableRewardExpiry: fetchedData.hasOwnProperty('enableRewardExpiry') ? fetchedData.enableRewardExpiry : initialFormData.enableRewardExpiry,
                        rewardCouponValidity: fetchedData.hasOwnProperty('rewardCouponValidity') ? fetchedData.rewardCouponValidity : initialFormData.rewardCouponValidity,
                        enableRewardCouponUsageLimit: fetchedData.hasOwnProperty('enableRewardCouponUsageLimit') ? fetchedData.enableRewardCouponUsageLimit : initialFormData.enableRewardCouponUsageLimit,
                        enableRewardDelayTime: fetchedData.hasOwnProperty('enableRewardDelayTime') ? fetchedData.enableRewardDelayTime : initialFormData.enableRewardDelayTime,
                        rewardDelayTime: fetchedData.hasOwnProperty('rewardDelayTime') ? fetchedData.rewardDelayTime : initialFormData.rewardDelayTime,
                        rewardCouponUsageLimit: fetchedData.hasOwnProperty('rewardCouponUsageLimit') ? fetchedData.rewardCouponUsageLimit : initialFormData.rewardCouponUsageLimit,
                        rewardOrderStatus: fetchedData.hasOwnProperty('rewardOrderStatus') ? fetchedData.rewardOrderStatus : initialFormData.rewardOrderStatus,
                        rewardIncludeProducts: fetchedData.hasOwnProperty('rewardIncludeProducts') ? fetchedData.rewardIncludeProducts : initialFormData.rewardIncludeProducts,
                        rewardExcludeProducts: fetchedData.hasOwnProperty('rewardExcludeProducts') ? fetchedData.rewardExcludeProducts : initialFormData.rewardExcludeProducts,
                        rewardIncludeCategories: fetchedData.hasOwnProperty('rewardIncludeCategories') ? fetchedData.rewardIncludeCategories : initialFormData.rewardIncludeCategories,
                        rewardExcludeCategories: fetchedData.hasOwnProperty('rewardExcludeCategories') ? fetchedData.rewardExcludeCategories : initialFormData.rewardExcludeCategories,
                        enableRefferalEmailInvitation: fetchedData.hasOwnProperty('enableRefferalEmailInvitation') ? fetchedData.enableRefferalEmailInvitation : initialFormData.enableRefferalEmailInvitation,
                        referralEmailSubject: fetchedData.hasOwnProperty('referralEmailSubject') ? fetchedData.referralEmailSubject : initialFormData.referralEmailSubject,
                        referralEmailHeading: fetchedData.hasOwnProperty('referralEmailHeading') ? fetchedData.referralEmailHeading : initialFormData.referralEmailHeading,
                        referralEmailBody: fetchedData.hasOwnProperty('referralEmailBody') ? fetchedData.referralEmailBody : initialFormData.referralEmailBody,
                        enableRewardEmailInvitation: fetchedData.hasOwnProperty('enableRewardEmailInvitation') ? fetchedData.enableRewardEmailInvitation : initialFormData.enableRewardEmailInvitation,
                        rewardEmailSubject: fetchedData.hasOwnProperty('rewardEmailSubject') ? fetchedData.rewardEmailSubject : initialFormData.rewardEmailSubject,
                        rewardEmailHeading: fetchedData.hasOwnProperty('rewardEmailHeading') ? fetchedData.rewardEmailHeading : initialFormData.rewardEmailHeading,
                        rewardEmailBody: fetchedData.hasOwnProperty('rewardEmailBody') ? fetchedData.rewardEmailBody : initialFormData.rewardEmailBody,
                        referralMenuIcon: fetchedData.hasOwnProperty('referralMenuIcon') ? fetchedData.referralMenuIcon : initialFormData.referralMenuIcon,
                    };

                    setFormData(updatedFormData);
                    setLastSavedFormData(updatedFormData);
                }
            } else {
                setError(response.data.data || 'Failed to fetch data');
            }
        } catch (error) {
            console.error('Error fetching data:', error);
            setError('Error fetching data');
        } finally {
            setLoading(false);
        }
    };

    const fetchReferralCoupon = async () => {
        try {
            const referralCouponToSend = new FormData();
            referralCouponToSend.append('action', 'ecre_fetch_referral_coupon');
            referralCouponToSend.append('nonce', ecreAdmin.nonce);

            const response = await axios.post(ecreAdmin.ajaxurl, referralCouponToSend, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                },
            });

            if (response.data.success) {
                const fetchedData = response.data.data;

                if (fetchedData) {
                    setReferralCoupon(fetchedData);
                }
            } else {
                console.error('Error fetching data');
            }
        } catch (error) {
            console.error('Error fetching data:', error);
        } finally {
            setLoading(false);
        }
    };

    const fetchProductsAndCategories = async () => {
        try {
            const dataToSend = new FormData();
            dataToSend.append('action', 'fetch_products_and_categories');
            dataToSend.append('nonce', ecreAdmin.nonce);
    
            const response = await axios.post(ecreAdmin.ajaxurl, dataToSend, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                },
            });
    
            if (response.data.success) {
                const fetchedData = response.data.data;
    
                if (fetchedData) {
                    const { products, categories } = fetchedData;
    
                    // Convert the products and categories to the desired format
                    const formattedProducts = products.map(product => ({
                        value: product.id,
                        label: product.text
                    }));
    
                    const formattedCategories = categories.map(category => ({
                        value: category.id,
                        label: category.text
                    }));
                  
                    // Update your state or DOM with the converted data
                    setProducts(formattedProducts);
                    setCategories(formattedCategories);
                }
            } else {
                console.error('Error fetching data');
            }
        } catch (error) {
            console.error('Error fetching data:', error);
        } finally {
            setLoading(false);
        }
    };

    const fetchAllPages = async () => {
        try {
            const dataToSend = new FormData();
            dataToSend.append('action', 'fetch_wp_pages');
            dataToSend.append('nonce', ecreAdmin.nonce);
    
            const response = await axios.post(ecreAdmin.ajaxurl, dataToSend, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                },
            });
    
            if (response.data.success) {
                const fetchedData = response.data.data;
                setPagesOptions(fetchedData);

            } else {
                console.error('Error fetching data');
            }
        } catch (error) {
            console.error('Error fetching data:', error);
        } finally {
            setLoading(false);
        }
    };
    
    // Call fetchData when the component mounts
    useEffect(() => {
        fetchData();
        fetchAllPages();
        fetchReferralCoupon();
        fetchProductsAndCategories();
    }, []);

    let referral_discount;
    let reward_discount;
    
    if (formData.referralCouponType.value === 'percent') {
        referral_discount = formData.referralDiscount + '%';
    } else {
        referral_discount = formData.referralDiscount + ecreAdmin.currency;
    }
    
    if (formData.rewardType.value === 'percent') {
        reward_discount = formData.rewardDiscount + '%';
    } else {
        reward_discount = formData.rewardDiscount + ecreAdmin.currency;
    }
    
    const handleToggle = (field) => (e) => {
        setFormData({ ...formData, [field]: e.target.checked });
        setHasChanges(true);
    };
    
    const handleInputChange = (field) => (e) => {
        const value = e.target.type === 'checkbox' ? e.target.checked : e.target.value;
        setFormData((prevFormData) => ({ ...prevFormData, [field]: value }));
        setHasChanges(true);
    };

    const handleSelectChange = (field) => (selectedOption) => {
        setFormData(prevFormData => ({
            ...prevFormData,
            [field]: selectedOption // Handle as an array for multi-select, or a single object for single-select
        }));
        setHasChanges(true);
    };

    const handleSocialSelectChange = (selectedOptions) => {
        const formattedOptions = selectedOptions.map(option => ({
            label: option.label,
            value: option.value,
        }));
        setFormData(prevFormData => ({
            ...prevFormData,
            socialMediaOptions: formattedOptions
        }));
        setHasChanges(true);
    };
    
    const handleImageUpload = (key, url) => {
        setFormData((prevFormData) => ({
            ...prevFormData,
            [key]: url
        }));
        setHasChanges(true);
    };

    const handleReset = () => {
        setFormData(lastSavedFormData);
        setHasChanges(false);
    };
    
    const handleSave = async () => {
        try {
            const formDataToSend = new FormData();
            formDataToSend.append('action', 'ecre_save_settings');
            formDataToSend.append('nonce', ecreAdmin.nonce);
            formDataToSend.append('settings', JSON.stringify(formData)); // Convert the formData to JSON string

            const response = await axios.post(ecreAdmin.ajaxurl, formDataToSend, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                },
            });

            if (response.data.success) {
                Siz.success('Settings saved!', 4000)

                setHasChanges(false);
            } else {
                Siz.error('Ops!', 'Something went wrong!')
                console.error('Failed to save settings:', response.data.data || 'Failed to save settings');
            }
        } catch (error) {
            console.error('Error saving settings:', error);
        }
    };

    useEffect(() => {
        if (!isCollapsed) {
            setTimeout(() => {
                setIsVisible(true);
            }, 100);
        }
    }, [isCollapsed]);

    // In SettingsApp.jsx or SettingsContext.js
    useEffect(() => {
        // Get the tab from URL if present
        const urlParams = new URLSearchParams(window.location.search);
        const tabParam = urlParams.get('tab');
        if(tabParam == 'reward_management') {
            const savedScreen = localStorage.getItem('ecre-active-screen');
            // Fix: Don't set null, use default
            if (savedScreen && savedScreen !== 'null') {
                setEcreActiveScreen(savedScreen);
            } else {
                setEcreActiveScreen('reward_management');
                localStorage.setItem('ecre-active-screen', 'reward_management');
            }
        }else {
            setEcreActiveScreen('reward_management');
            localStorage.setItem('ecre-active-screen', 'reward_management');
            
            // reset ecre-referrer-tab switch to main setting tab
            localStorage.setItem('ecre-referrer-tab', 'referral-history');
            setActiveReferrerTab('referral-history');
        }
        
        if (tabParam) {
            setActiveTab(tabParam);
            localStorage.setItem('active-tab', tabParam);
        } else {
            setActiveTab(localStorage.getItem('active-tab') || 'referral_settings');
            setEcreActiveScreen(localStorage.getItem('ecre-active-screen') || 'reward_management');
        }
    }, []);

    useEffect(() => {
        // Get the tab from URL if present
        const urlParams = new URLSearchParams(window.location.search);
        const tabParam = urlParams.get('tab');
        if(tabParam == 'reward_management') {
            const savedScreen = localStorage.getItem('ecre-active-screen');
            // Fix: Don't set null, use default
            if (savedScreen && savedScreen !== 'null') {
                setEcreActiveScreen(savedScreen);
            } else {
                setEcreActiveScreen('reward_management');
                localStorage.setItem('ecre-active-screen', 'reward_management');
            }
        }else {
            setEcreActiveScreen('reward_management');
            localStorage.setItem('ecre-active-screen', 'reward_management');
            // reset ecre-referrer-tab switch to main setting tab
            localStorage.setItem('ecre-referrer-tab', 'referral-history');
            setActiveReferrerTab('referral-history');
        }
    }, [activeTab]);

    const handleCollapse = () => {
        setIsCollapsed(!isCollapsed);
        setIsVisible(false);
    };

    const handleActiveTab = (name) => {
        // Update localStorage and state
        localStorage.setItem('active-tab', name);
        setActiveTab(name);
        
        // Update the URL when tab changes (without page reload)
        const newUrl = `admin.php?page=echo-rewards&tab=${name}`;
        window.history.pushState({ path: newUrl }, '', newUrl);
        
        // Optionally, add class to highlight the submenu (may not be necessary)
        const submenuItems = document.querySelectorAll('#adminmenu .wp-submenu li');
        submenuItems.forEach(item => {
            item.classList.remove('current');
            if (item.querySelector('a')?.href.includes(`tab=${name}`)) {
                item.classList.add('current');
            }
        });
    };
    const handleActiveScreen = (name) => {
        // Update localStorage and state
        localStorage.setItem('ecre-active-screen', name);
        setEcreActiveScreen(name);

        // Clear selected referrer when going back to main screen
        if (name === 'reward_management') {
            setSelectedReferrer(null);
            localStorage.removeItem('ecre-selected-referrer');
        }
    };
    const handleActiveReferrerTab = (name) => {
        // Update localStorage and state
        localStorage.setItem('ecre-referrer-tab', name);
        setActiveReferrerTab(name);
    };

    const handleToggleModal = () => {
        setIsOpen(!isOpen);
    };

    const handleToggleReferralModal = () => {
        setIsReferralMailModal(!isReferralMailModal);
    };

    const handleToggleReferralTagModal = () => {
        setIsReferralMailTagModal(!isReferralMailTagModal);
    };

    const handleToggleRewardTagModal = () => {
        setIsRewardMailTagModal(!isRewardMailTagModal);
    };

    const handleToggleRewardModal = () => {
        setIsRewardMailModal(!isRewardMailModal);
    };

    const referralCouponTypeOptions = useMemo(() => [
        { value: 'percent', label: ecreAdmin.strings.coupon_type_percentage },
        { value: 'fixed', label: ecreAdmin.strings.coupon_type_fixed },
        { value: 'sign_up_fee', label: ecreAdmin.strings.coupon_type_sign_up_fee },
        { value: 'sign_up_fee_percent', label: ecreAdmin.strings.coupon_type_sign_up_fee_percent },
        { value: 'recurring_fee', label: ecreAdmin.strings.coupon_type_recurring_fee },
        { value: 'recurring_percent', label: ecreAdmin.strings.coupon_type_recurring_percent },
    ], []);


    const orderStatusOptions = useMemo(() => {
        return ecreAdmin.woocommerce_order_statuses || [];
    }, []);

    const rewardCouponTypeOptions = useMemo(() => [
        { value: 'percent', label: ecreAdmin.strings.coupon_type_percentage },
        { value: 'fixed', label: ecreAdmin.strings.coupon_type_fixed },
        { value: 'reward_point', label: ecreAdmin.strings.coupon_type_reward_point },
        { value: 'sign_up_fee', label: ecreAdmin.strings.coupon_type_sign_up_fee },
        { value: 'sign_up_fee_percent', label: ecreAdmin.strings.coupon_type_sign_up_fee_percent },
        { value: 'recurring_fee', label: ecreAdmin.strings.coupon_type_recurring_fee },
        { value: 'recurring_percent', label: ecreAdmin.strings.coupon_type_recurring_percent },
    ], []);

    const rewardPointExpiryOptions = useMemo(() => [
        { value: 'unavailable', label: ecreAdmin.strings.reward_expiry_action_unavailable },
        { value: 'delete', label: ecreAdmin.strings.reward_expiry_action_delete },
    ], []);

    const referralFloatingWidgetOptions = useMemo(() => [
        { value: 'left', label: ecreAdmin.strings.floating_widget_vertical_left },
        { value: 'right', label: ecreAdmin.strings.floating_widget_vertical_right },
    ], []);

    const socialMediaOptions = useMemo(() => [
        { value: 'Facebook', label: 'Facebook', icon: <Facebook /> },
        { value: 'WhatsApp', label: 'WhatsApp', icon: <WhatsApp /> },
        { value: 'Twitter', label: 'X (Twitter)', icon: <TwitterX /> },
        { value: 'Messenger', label: 'Messenger', icon: <Messenger /> },
        { value: 'Linkedin', label: 'Linkedin', icon: <Linkedin /> },
        { value: 'Gmail', label: 'Gmail', icon: <Gmail /> },
        { value: 'Line', label: 'Line', icon: <Line /> },
        { value: 'Outlook', label: 'Outlook', icon: <Outlook /> },
        { value: 'WeChat', label: 'WeChat', icon: <WeChat /> },
        { value: 'Telegram', label: 'Telegram', icon: <Telegram /> },
        { value: 'Skype', label: 'Skype', icon: <Skype /> },
        { value: 'Trello', label: 'Trello', icon: <Trello /> },
    ], []);

    const handleCopy = (shortcode, index) => {
        const tempTextArea = document.createElement('textarea');
        tempTextArea.value = shortcode;
        document.body.appendChild(tempTextArea);

        tempTextArea.select();
        document.execCommand('copy');

        document.body.removeChild(tempTextArea);

        setCopiedItemIndex(index);

        // Reset copy status after a short delay
        setTimeout(() => setCopiedItemIndex(null), 1500);
    };

    const currency = ecreAdmin.currency;


    const contextValue = useMemo(() => ({
        activeTab, handleActiveTab,
        ecreActiveScreen, handleActiveScreen,
        activeReferrerTab, handleActiveReferrerTab,
        isCollapsed, handleCollapse,
        isVisible,
        isOpen, handleToggleModal,
        isReferralMailModal, handleToggleReferralModal,
        isReferralMailTagModal,handleToggleReferralTagModal,
        isRewardMailModal, handleToggleRewardModal,
        isRewardMailTagModal, handleToggleRewardTagModal,
        formData, setFormData, handleToggle, handleInputChange, handleSelectChange, handleImageUpload, hasChanges, handleReset, handleSave,handleSocialSelectChange,
        referralCouponTypeOptions,orderStatusOptions,
        rewardCouponTypeOptions,rewardPointExpiryOptions,
        referralFloatingWidgetOptions,
        woocommerceProductOptions,pagesOptions,
        woocommerceProductCategoryOptions,
        socialMediaOptions,currency,
        CustomOption, CouponTypeProOption, SubscriptionProOption, handleCopy, copiedItemIndex, setCopiedItemIndex, referralCoupon, referral_discount, reward_discount,isPro,loading,initialFormData,selectedReferrer,setSelectedReferrer: handleSetSelectedReferrer,referrerDetailsSummary, setReferrerDetailsSummary,
    }), [
        activeTab, ecreActiveScreen, activeReferrerTab, isCollapsed, isVisible, isOpen,
        isReferralMailModal,isReferralMailTagModal, isRewardMailModal, isRewardMailTagModal, pagesOptions,
        referralCouponTypeOptions, orderStatusOptions, rewardCouponTypeOptions, rewardPointExpiryOptions, referralFloatingWidgetOptions,
        woocommerceProductOptions, woocommerceProductCategoryOptions,
        socialMediaOptions, CustomOption, CouponTypeProOption, SubscriptionProOption, formData, copiedItemIndex, hasChanges,isPro,loading,selectedReferrer, referrerDetailsSummary, 
    ]);

    return (
        <SettingsContext.Provider value={contextValue}>
            {children}
        </SettingsContext.Provider>
    );
};

export { SettingsContext, SettingsProvider };
