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

const FrontendContext = createContext();

const FrontendProvider = ({ children }) => {
    const [settings, setSettings] = useState({});
    const [referralCoupon, setReferralCoupon] = useState({});
    const [inviteCoupons, setInviteCoupons] = useState({});
    const [rewardCoupons, setRewardCoupons] = useState({});
    const [rewardpoints, setRewardpoints] = useState({});
    const [loadingSettings, setLoadingSettings] = useState(false);
    const [loadingReferralCoupon, setLoadingReferralCoupon] = useState(false);
    const [loadingInvitesCoupon, setLoadingInvitesCoupon] = useState(false);
    const [loadingRewardCoupon, setLoadingRewardCoupon] = useState(false);
    const [loadingRewardPoints, setLoadingRewardPoints] = useState(false);
    const [copiedItemIndex, setCopiedItemIndex] = useState(null);
    const [isReferralShareModal, setIsReferralShareModal] = useState(false);
    const [isPro, setIsPro] = useState(ecreFrontend.is_pro);
    const default_settings = ecreFrontend.default_settings;

    const fetchSettings = async () => {
        try {
            setLoadingSettings(true);
            const settingsDataToSend = new FormData();
            settingsDataToSend.append('action', 'ecre_fetch_settings');
            settingsDataToSend.append('nonce', ecreFrontend.nonce);

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

            if (response.data.success) {
                const fetchedData = response.data.data;
                if (fetchedData) setSettings(fetchedData);
                setLoadingSettings(false);
            } else {
                console.error('Error fetching data');
            }
        } catch (error) {
            console.error('Error fetching data:', error);
        } finally {
           // setLoadingSettings(false);
        }
    };

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

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

            if (response.data.success) {
                const fetchedData = response.data.data;
                if (fetchedData) setReferralCoupon(fetchedData);
                setLoadingReferralCoupon(false);
            } else {
                console.error('Error fetching data');
            }
        } catch (error) {
            console.error('Error fetching data:', error);
        } finally {
           // setLoadingReferralCoupon(false);
        }
    };

    const fetchReferralInvitesCoupon = async () => {
        try {
            setLoadingInvitesCoupon(true);
            const referralCouponToSend = new FormData();
            referralCouponToSend.append('action', 'ecre_fetch_invite_coupons');
            referralCouponToSend.append('nonce', ecreFrontend.nonce);

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

            if (response.data.success) {
                const fetchedData = response.data.data;
                if (fetchedData) setInviteCoupons(fetchedData);
                setLoadingInvitesCoupon(false);
            } else {
                console.error('Error fetching data');
            }
        } catch (error) {
            console.error('Error fetching data:', error);
        } finally {
           // setLoadingInvitesCoupon(false);
        }
    };

    const fetchRewardCouponData = async () => {
        setLoadingRewardCoupon(true);
        try {
            const rewardsDataToSend = new FormData();
            rewardsDataToSend.append('action', 'ecre_fetch_reward_coupons');
            rewardsDataToSend.append('nonce', ecreFrontend.nonce);

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

            if (response.data.success) {
                const fetchedData = response.data.data;
                if (fetchedData) setRewardCoupons(fetchedData);
                setLoadingRewardCoupon(false);
            } else {
                console.error('Error fetching data');
            }
        } catch (error) {
            console.error('Error fetching data:', error);
        } finally {
           // setLoadingRewardCoupon(false);
        }
    };

    const fetchRewardPointsData = async () => {
        setLoadingRewardPoints(true);
        try {
            const rewardsPointDataToSend = new FormData();
            rewardsPointDataToSend.append('action', 'ecre_fetch_reward_points');
            rewardsPointDataToSend.append('nonce', ecreFrontend.nonce);

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

            if (response.data.success) {
                const fetchedData = response.data.data;
                if (fetchedData) setRewardpoints(fetchedData);
                setLoadingRewardPoints(false);
            } else {
                console.error('Error fetching data');
            }
        } catch (error) {
            console.error('Error fetching data:', error);
        } finally {
            //setLoadingRewardPoints(false);
        }
    };


    useEffect(() => {
        fetchSettings();
        fetchReferralCoupon();
        fetchReferralInvitesCoupon();
        fetchRewardCouponData();
        
        if(isPro) {
            fetchRewardPointsData();
        }
        
    }, []);

    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);
    };

    // Share modal
    const handleToggleReferralShareModal = () => {
        setIsReferralShareModal(!isReferralShareModal);
    };

    var message = '';
    var RefLinkMessage = '';
    var RefLinkEncodedUrl = '';
    const currency = ecreFrontend.currency;
    let referralDiscountType = '';
    let rewardlDiscountType = '';
    let filteredSocialMediaOptions = {};

    if( !loadingSettings && Object.keys(settings).length > 0 && !loadingReferralCoupon ){
        message = `Use the code ${referralCoupon.coupon_code} to get ${settings.referralDiscount}${settings.referralCouponType.value === 'percent' ? '%' : `${currency}`} off on ${ecreFrontend.site_url}.`;
        RefLinkMessage = `Use the referral link to get ${settings.referralDiscount}${settings.referralCouponType.value === 'percent' ? '%' : `${currency}`} off. Referral link: ${ecreFrontend.site_url}/?ref=${referralCoupon.coupon_code.toLowerCase()}.`;
        RefLinkEncodedUrl = encodeURIComponent(`${ecreFrontend.site_url}/?ref=${referralCoupon.coupon_code.toLowerCase()}`);
        // Get discount type from settings
        const settingsReferralDiscountType = settings.referralCouponType?.value;
        const settingsRewardlDiscountType = settings.rewardType.value;
        // Apply the logic
        referralDiscountType = !isPro && settingsReferralDiscountType  !== 'percent' && settingsReferralDiscountType  !== 'fixed'
            ? default_settings.referralCouponType?.value
            : settingsReferralDiscountType ;

        rewardlDiscountType = !isPro && settingsRewardlDiscountType  !== 'percent' && settingsRewardlDiscountType  !== 'fixed'
            ? default_settings.referralCouponType?.value
            : settingsRewardlDiscountType ;

        // Use default_settings to determine free social media options
        const freeSocialMedia = default_settings.socialMediaOptions.map(option => option.value);

        // Filter social media options based on isPro
        filteredSocialMediaOptions = isPro
            ? settings.socialMediaOptions // If Pro, keep all
            : settings.socialMediaOptions.filter(option => freeSocialMedia.includes(option.value)); // Otherwise, keep only free options
    }


    const encodedMessage = encodeURIComponent(message);
    const encodedUrl = encodeURIComponent(ecreFrontend.site_url);
    const RefLinkEncodedMessage = encodeURIComponent(RefLinkMessage);


    
    const socialMediaComponents = {
        Facebook: {
            icon: Facebook,
            label: "Facebook",
            url: `https://www.facebook.com/sharer/sharer.php?u=${encodedUrl}&quote=${encodedMessage}`,
        },
        Messenger: {
            icon: Messenger,
            label: "Messenger",
            url: `https://www.messenger.com/t/?link=${encodedUrl}&quote=${encodedMessage}`,
        },
        Linkedin: {
            icon: Linkedin,
            label: "Linkedin",
            url: `https://www.linkedin.com/shareArticle?mini=true&url=${encodedUrl}&text=${encodedMessage}`,
        },
        Twitter: {
            icon: TwitterX,
            label: "X (Twitter)",
            url: `https://twitter.com/intent/tweet?text=${encodedMessage}`,
        },
        Gmail: {
            icon: Gmail,
            label: "Gmail",
            url: `https://mail.google.com/mail/?view=cm&fs=1&to=&su=&body=${encodedMessage}`,
        },
        Line: {
            icon: Line,
            label: "Line",
            url: `https://lineit.line.me/share/ui?url=${encodedUrl}&text=${encodedMessage}`,
        },
        Outlook: {
            icon: Outlook,
            label: "Outlook",
            url: `mailto:?subject=Special%20Offer&body=${encodedMessage}`,
        },
        WeChat: {
            icon: WeChat,
            label: "WeChat",
            url: `https://api.qrserver.com/v1/create-qr-code/?size=154x154&data=${encodedMessage}`,
        },
        WhatsApp: {
            icon: WhatsApp,
            label: "WhatsApp",
            url: `https://wa.me/?text=${encodedMessage}`,
        },
        Telegram: {
            icon: Telegram,
            label: "Telegram",
            url: `https://t.me/share/url?url=${encodedUrl}&text=${encodedMessage}`,
        },
        Skype: {
            icon: Skype,
            label: "Skype",
            url: `https://web.skype.com/share?url=${encodedUrl}&text=${encodedMessage}`,
        },
        Trello: {
            icon: Trello,
            label: "Trello",
            url: `https://trello.com/add-card?mode=popup&url=${encodedUrl}&desc=${encodedMessage}`,
        },
    };

    const socialMediaComponentsForRefLink = {
        Facebook: {
            icon: Facebook,
            label: "Facebook",
            url: `https://www.facebook.com/sharer/sharer.php?u=${RefLinkEncodedUrl}&quote=${RefLinkEncodedMessage}`,
        },
        Messenger: {
            icon: Messenger,
            label: "Messenger",
            url: `https://www.messenger.com/t/?link=${RefLinkEncodedUrl}&quote=${RefLinkEncodedMessage}`,
        },
        Linkedin: {
            icon: Linkedin,
            label: "Linkedin",
            url: `https://www.linkedin.com/shareArticle?mini=true&url=${RefLinkEncodedUrl}&text=${RefLinkEncodedMessage}`,
        },
        Twitter: {
            icon: TwitterX,
            label: "X (Twitter)",
            url: `https://twitter.com/intent/tweet?text=${RefLinkEncodedMessage}`,
        },
        Gmail: {
            icon: Gmail,
            label: "Gmail",
            url: `https://mail.google.com/mail/?view=cm&fs=1&to=&su=&body=${RefLinkEncodedMessage}`,
        },
        Line: {
            icon: Line,
            label: "Line",
            url: `https://lineit.line.me/share/ui?url=${RefLinkEncodedUrl}&text=${RefLinkEncodedMessage}`,
        },
        Outlook: {
            icon: Outlook,
            label: "Outlook",
            url: `mailto:?subject=Special%20Offer&body=${RefLinkEncodedMessage}`,
        },
        WeChat: {
            icon: WeChat,
            label: "WeChat",
            url: `https://api.qrserver.com/v1/create-qr-code/?size=154x154&data=${RefLinkEncodedMessage}`,
        },
        WhatsApp: {
            icon: WhatsApp,
            label: "WhatsApp",
            url: `https://wa.me/?text=${RefLinkEncodedMessage}`,
        },
        Telegram: {
            icon: Telegram,
            label: "Telegram",
            url: `https://t.me/share/url?url=${RefLinkEncodedUrl}&text=${RefLinkEncodedMessage}`,
        },
        Skype: {
            icon: Skype,
            label: "Skype",
            url: `https://web.skype.com/share?url=${RefLinkEncodedUrl}&text=${RefLinkEncodedMessage}`,
        },
        Trello: {
            icon: Trello,
            label: "Trello",
            url: `https://trello.com/add-card?mode=popup&url=${RefLinkEncodedUrl}&desc=${RefLinkEncodedMessage}`,
        },
    };
    
    const contextValue = useMemo(() => ({
        settings,
        referralCoupon,
        inviteCoupons,rewardCoupons,rewardpoints,
        loadingSettings, loadingReferralCoupon, loadingInvitesCoupon, loadingRewardCoupon, loadingRewardPoints,
        copiedItemIndex,
        handleCopy,
        handleToggleReferralShareModal,isReferralShareModal,socialMediaComponents,socialMediaComponentsForRefLink,isPro,default_settings,referralDiscountType,rewardlDiscountType,filteredSocialMediaOptions,currency
    }), [settings, referralCoupon, inviteCoupons,rewardCoupons,rewardpoints,  loadingSettings, loadingReferralCoupon, loadingInvitesCoupon, loadingRewardCoupon, loadingRewardPoints, copiedItemIndex, isReferralShareModal,isPro]);

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

export { FrontendContext, FrontendProvider };
