import React, {useState,useContext} from "react";
import Modal from '../../components/core/Modal';
import winRewardImage from '../../images/win-rewards.png'
import ecreIcons from "../../components/core/icons";
import { FrontendContext } from "./FrontendContext";
import Loader from "../../components/core/Loader";
import { translate } from "../../Helper";

function FloatingWidget() {
   
    const { isPro,loadingSettings, settings,referralCoupon,handleCopy,copiedItemIndex,handleToggleReferralShareModal,isReferralShareModal,socialMediaComponents, socialMediaComponentsForRefLink, rewardlDiscountType  } = useContext(FrontendContext);

    const [isOpen, setIsOpen] = useState(false);
    const [shareType, setShareType] = useState(null);


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


    const toggleReferralShareModal = (type) => {
        setShareType(type);
        handleToggleReferralShareModal();
    };

    var widget_position = settings.referralWidgetPosition? settings.referralWidgetPosition.value : '';


    if ( (!referralCoupon || Object.keys(referralCoupon ).length === 0) || (!settings || Object.keys(settings).length === 0)) {
        return <Loader />;
    }

    const selectedSocialMediaComponents = shareType === 'refLink'
    ? socialMediaComponentsForRefLink
    : socialMediaComponents;
  

    return (
         
        <>
            <div onClick={handleToggleModal} className={`echo-rewards-floatingwidget ecre-z-[2]  ecre-transition ecre-cursor-pointer ecre-fixed ${ 'left' == widget_position ? 'floatingwidget-left ecre-left-0 ecre-origin-top-left ecre-rounded-bl-[10px] ecre-rounded-br-[10px]' : 'floatingwidget-right ecre-right-[2%] ecre-origin-top-right ecre-rounded-tl-[10px] ecre-rounded-tr-[10px]' } ecre-rotate-[270deg] ecre-text-white ecre-text-sm ecre-font-semibold  ecre-px-5 ecre-pt-2 ecre-pb-3 ecre-bg-violet-600  ecre-inline-flex ecre-items-center ecre-gap-1.5 hover:ecre-bg-violet-700`}>
                <div className="icon">
                    {ecreIcons.giftWhite}
                </div>
                <span>{translate('refer_and_win')} </span>
            </div>

            {ecreFrontend.is_user_logged_in ? ( 
               (settings.canRefferOthers && ecreFrontend.has_orders) || !settings.canRefferOthers ? (
                    <Modal openModal={isOpen} toggleModal={handleToggleModal}>
                        {{
                        header: <div className="ecre-text-neutral-950 ecre-text-lg ecre-text-center md:ecre-text-2xl ecre-font-medium ecre-leading-[1.2] ecre-w-full">{translate('refer_and_win_exciting_rewards')}</div>,
                        body: (
                            <>
                                <div className="ecre-text-center ecre-mt-[-10px] ecre-text-zinc-500 ecre-text-xs ecre-font-normal ecre-mb-5"> {translate('share_referral_code')}</div>
                                <figure className="media ecre-flex ecre-justify-center ecre-w-full ecre-mb-5">
                                    <img src={winRewardImage} className=" !ecre-max-w-[140px]" alt="" />
                                </figure>
                                <div className="reward-coupon ecre-text-center">
                                    <h6 className="ecre-text-zinc-500 ecre-text-sm ecre-font-medium ecre-mb-2">
                                        {translate('use_referral_coupon_code')}</h6>
                                    <div className="ecre-text-zinc-700 ecre-text-lg md:ecre-text-xl ecre-font-bold md:ecre-leading-[30px] ecre-mb-3">{referralCoupon.coupon_code}</div>

                                    {referralCoupon.discount_type === 'sign_up_fee' || referralCoupon.discount_type === 'sign_up_fee_percent' ? (
                                        <div class="ecre-text-neutral-500 ecre-text-xs ecre-font-normal ecre-leading-[18px] ecre-mb-4">
                                            {settings.referralSignupCouponNote}
                                        </div>
                                    ) : referralCoupon.discount_type === 'recurring_fee' || referralCoupon.discount_type === 'recurring_percent'
                                        ? (
                                            <div class="ecre-text-neutral-500 ecre-text-xs ecre-font-normal ecre-leading-[18px] ecre-mb-4">
                                                {settings.referralRecurringCouponNote}
                                            </div>
                                        ) : ''
                                    }

                                    {settings.enableReferralLimit && (
                                            <div
                                                className={`ecre-text-xs ecre-font-medium ecre-mb-2 ${referralCoupon.is_monthly_limit_reached ? 'ecre-text-red-500' : 'ecre-text-[#219653]'
                                                    }`}
                                            >
                                                {referralCoupon.is_monthly_limit_reached
                                                    ? translate('you_have_reached_referral_limit')
                                                    :    `${translate('you_have')} ${referralCoupon.current_referral_limit}  ${translate('referrals_remaining')}`}
                                            </div>
                                    )}

                                    <div className="btn-box ecre-flex ecre-justify-center ecre-items-center ecre-gap-2.5 ecre-mb-3">
                                        <button
                                            className={`ecre-w-20 ecre-group ecre-px-2 ecre-py-[6px] ecre-bg-violet-600 ecre-cursor-pointer ecre-border-0 ecre-rounded-[5px] ecre-text-white ecre-text-[10px] ecre-font-normal ecre-inline-flex ecre-items-center ecre-justify-center ecre-gap-1 ecre-transition hover:ecre-bg-violet-500 focus:ecre-bg-violet-500 ${settings.enableReferralLimit && referralCoupon.is_monthly_limit_reached ? 'ecre-opacity-50 ecre-cursor-not-allowed' : ''}`}
                                            onClick={() => handleCopy(referralCoupon.coupon_code, 0)}
                                            disabled={settings.enableReferralLimit && referralCoupon.is_monthly_limit_reached}
                                        >
                                            <span className="icon">
                                                {ecreIcons.copy_coupon}
                                            </span>
                                            <span>
                                                {copiedItemIndex === 0 ?   translate('copied') : translate('copy')}
                                            </span>
                                        </button>


                                        {settings.enableReferralSocialSharing && (
                                            <button
                                                onClick={() => toggleReferralShareModal('general')}
                                                className={`ecre-w-20 ecre-group ecre-px-2 ecre-py-[6px] ecre-bg-[#E7DDF4] ecre-cursor-pointer ecre-border-0 lea ecre-rounded-[5px] ecre-text-[#452D7E] ecre-text-[10px] ecre-font-normal ecre-inline-flex ecre-items-center ecre-justify-center ecre-gap-1 ecre-transition hover:ecre-bg-[#452D7E] hover:ecre-text-white focus:ecre-bg-[#452D7E] focus:ecre-text-white ${settings.enableReferralLimit && referralCoupon.is_monthly_limit_reached ? 'ecre-opacity-50 ecre-cursor-not-allowed' : ''}`}
                                                disabled={settings.enableReferralLimit && referralCoupon.is_monthly_limit_reached}
                                            >
                                                <span className="icon">
                                                    {ecreIcons.sendEmail}
                                                </span>
                                                <span>{ translate('share')}</span>
                                            </button>
                                        )}
                                    </div> 


                                    { settings.enableReferralLink && (
                                        <>
                                            <div className="ecre-text-zinc-500 ecre-text-[13px] ecre-font-medium ecre-mb-2"> {translate('or_use_your_referral_link')}  </div>
                                            <div className="share-link ecre-mb-4 ecre-flex ecre-justify-center">
                                                <div className="ecre-relative">
                                                    <input type="text" defaultValue={`${ecreFrontend.site_url}/?ref=${referralCoupon.coupon_code.toLowerCase()} `} disabled className={`!ecre-text-[#452D7E] !ecre-h-auto placeholder:!ecre-text-[#452D7E] ecre-min-w-[230px] sm:ecre-min-w-[276px] !ecre-shadow-none !ecre-text-xs !ecre-font-normal ecre-bg-white !ecre-p-2.5 !ecre-pr-[66px] !ecre-rounded-lg !ecre-box-border !ecre-border !ecre-border-solid !ecre-border-[#E7DDF4] focus:!ecre-border-solid ${settings.enableReferralLimit && referralCoupon.is_monthly_limit_reached ? 'ecre-opacity-50 ecre-cursor-not-allowed' : ''}`} />
                                                    <div className="ecre-btn-box ecre-flex ecre-justify-center ecre-items-center ecre-gap-1.5 ecre-absolute ecre-top-[7px] ecre-right-2">
                                                        <button className={`ecre-group ecre-p-1.5 ecre-bg-violet-600 ecre-cursor-pointer ecre-border-0 ecre-rounded-[5px] ecre-text-white ecre-text-[10px] ecre-font-normal ecre-inline-flex ecre-items-center ecre-justify-center ecre-gap-1 ecre-transition hover:ecre-bg-violet-500 focus:ecre-bg-violet-500 ${settings.enableReferralLimit && referralCoupon.is_monthly_limit_reached ? 'ecre-opacity-50 ecre-cursor-not-allowed' : ''}`}  onClick={() => handleCopy(`${ecreFrontend.site_url}/?ref=${referralCoupon.coupon_code.toLowerCase()}`, 1)}
                                                        disabled={settings.enableReferralLimit && referralCoupon.is_monthly_limit_reached}
                                                        >
                                                            <span className="icon">
                                                                {copiedItemIndex === 1 ? (ecreIcons.copiedChecked) : (ecreIcons.copy_coupon)}
                                                            </span>
                                                        </button>

                                                        {settings.enableReferralSocialSharing && (
                                                            <button className={`ecre-group ecre-p-1.5 ecre-bg-[#E7DDF4] ecre-cursor-pointer ecre-border-0 ecre-rounded-[5px] ecre-text-[#452D7E] ecre-text-[10px] ecre-font-normal ecre-inline-flex ecre-items-center ecre-justify-center ecre-gap-1 ecre-transition hover:ecre-bg-[#452D7E] hover:ecre-text-white focus:ecre-bg-[#452D7E] focus:ecre-text-white ${settings.enableReferralLimit && referralCoupon.is_monthly_limit_reached ? 'ecre-opacity-50 ecre-cursor-not-allowed' : ''}`}  onClick={() => toggleReferralShareModal('refLink')} disabled={settings.enableReferralLimit && referralCoupon.is_monthly_limit_reached}>
                                                                <span className="icon">
                                                                    {ecreIcons.sendEmail}
                                                                </span>
                                                            </button>
                                                        )}
                                                    </div>
                                                </div>
                                            </div>
                                        </>
                                    )}

                                    <div className="ecre-text-neutral-500 ecre-text-xs ecre-font-normal ecre-leading-[18px]">{translate('get_discount')} <strong className="ecre-text-[#5257C4] ecre-font-semibold">{referralCoupon.referral_discount} {translate('discount')}</strong> {rewardlDiscountType == 'reward_point' ? translate('with_this_coupon_you_will_get_point') : translate('with_this_coupon_you_will_get')} <strong className="ecre-text-[#D857ED] ecre-font-semibold ">{rewardlDiscountType == 'reward_point' ? settings.rewardPoint : referralCoupon.reward_discount} {rewardlDiscountType == 'reward_point' ? translate('points') : translate('discount')} </strong> {translate('each_time_someone_uses_your_coupon')}</div>
                                </div>
                            </>
                        )
                        }}
                    </Modal>
                ) : (
                    <Modal openModal={isOpen} toggleModal={handleToggleModal}>
                        {{
                        body: (
                            <div className="ecre-text-center -ecre-mt-2 ecre-mb-10">
                                <div className="ecre-text-[#0c0c0d] ecre-mb-4 ecre-text-2xl ecre-font-medium"> {translate('refer_and_win_rewards')}</div>
                                <div className="icon ecre-flex ecre-justify-center ecre-mb-4">
                                    {ecreIcons.noOrder}
                                </div>
                                <div className="ecre-max-w-[309px] ecre-mx-auto ecre-text-[#5e656a] ecre-text-xs ecre-font-normal ecre-leading-[18px]"><p>{settings.noOrderMessageToReferrer}</p></div>
                            </div>
                        )
                        }}
                    </Modal>
                )
            ) : (
                <Modal openModal={isOpen} toggleModal={handleToggleModal}>
                    {{
                    body: (
                        <div className="ecre-text-center ecre-mb-10">
                            <figure className="media ecre-flex ecre-justify-center ecre-w-full ecre-mb-5">
                                <img src={winRewardImage} className=" !ecre-max-w-[140px]" alt="" />
                            </figure>

                            <div className="ecre-text-[#0c0c0d] ecre-mb-2.5 ecre-text-2xl ecre-font-medium">{translate('refer_and_win_rewards')}</div>
                            <div className="ecre-max-w-[330px] ecre-mb-4 ecre-mx-auto ecre-text-[#686977] ecre-text-xs ecre-font-normal ">{translate('create_account_for_referral')}</div>
                            <button className="ecre-px-2.5 ecre-inline-flex ecre-items-center !ecre-shadow-none ecre-py-2.5 !ecre-bg-[#6d3ae6] ecre-cursor-pointer ecre-border-0 ecre-rounded-[5px] ecre-text-white ecre-text-[10px] ecre-font-normal ecre-transition hover:!ecre-bg-violet-800"
                            onClick={() => {
                                const siteUrl = ecreFrontend.site_url;
                                window.location.href = `${siteUrl}/my-account/`;
                            }}
                            >
                                <span className="icon ecre-mr-1">
                                    {ecreIcons.loginGift}
                                </span>
                               {translate('get_rewards_now')}
                            </button>
                        </div>
                    )
                    }}
                </Modal>
            )}

            { settings.socialMediaOptions ? 
            (<Modal className='social-share' openModal={isReferralShareModal} toggleModal={handleToggleReferralShareModal}>
                {{
                header: <div className="ecre-text-gray-700 ecre-text-xl ecre-font-semibold">{translate('share_on_social_media')}</div>,
                body: (
                    <ul className="social-list ecre-flex ecre-flex-wrap ecre-gap-6 ecre-list-none !ecre-px-0 !ecre-pt-5 !ecre-m-0 ecre-border-0 ecre-border-t ecre-border-solid ecre-border-[#f5f1fd]">
                    {settings.socialMediaOptions.map(option => {
                        const socialMedia = selectedSocialMediaComponents[option.value];
                        
                        if (!socialMedia) return null;

                        const IconComponent = socialMedia.icon;
                        const url = socialMedia.url;

                        return (
                        <li key={option.value}>
                            <a href={url} target="__blank" className=" !ecre-no-underline ecre-cursor-pointer ecre-flex-col ecre-justify-center ecre-items-center ecre-gap-2 ecre-inline-flex ecre-group">
                            <div className="icon-wrapper ecre-h-[60px] ecre-w-[60px] ecre-p-2 ecre-bg-white ecre-rounded-lg ecre-border-solid ecre-border ecre-border-gray-200 ecre-flex ecre-justify-center ecre-items-center ecre-transition group-hover:ecre-border-[#d0c2f5]">
                                <IconComponent />
                            </div>
                            <div className="ecre-text-center ecre-text-gray-400 ecre-text-sm ecre-font-normal ecre-transition group-hover:ecre-text-[#6a40d5]">
                                {socialMedia.label}
                            </div>
                            </a>
                        </li>
                        );
                    })}
                    </ul>
                )
                }}
            </Modal>) : ''}
        
        </>
        
    );
}

export default FloatingWidget;