import React, { useState, useContext, useEffect } from 'react';
import { FrontendContext } from '../../App/FrontendContext';
import Modal from '../../../components/core/Modal';
import ecreIcons from '../../../components/core/icons';
import Loader from '../../../components/core/Loader';
import { translate } from '../../../Helper';

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

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

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

    const [elSettings, setElSettings] = useState(settings_mx || {});

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

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


    return (
        <>
            {ecreFrontend.is_user_logged_in ? (
                (settings.canRefferOthers && ecreFrontend.has_orders) || !settings.canRefferOthers ? (
                    <>
                        <div className="reward-coupon ecre-px-4 ecre-py-5 sm:ecre-px-[22px] sm:ecre-py-6 ecre-bg-purple-50 ecre-rounded-[20px] ecre-text-center ecre-mb-6"
                            style={{
                                backgroundColor: elSettings.card_background_color || '#FBF9FF',
                            }}
                        >

                            <>
                                <h6 className="ecre-text-zinc-500 ecre-text-sm ecre-font-medium ecre-mb-2"> {elSettings.title || translate('use_referral_code')}</h6>
                                <div className="ecre-text-zinc-700 ecre-text-lg md:ecre-text-xl ecre-font-bold md:ecre-leading-[30px] ecre-mb-4">
                                    {referralCoupon.coupon_code}
                                </div>

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

                                {isPro && 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('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-4">
                                    <button className="ecre-w-20 ecre-group ecre-px-2 ecre-py-[5px] ecre-bg-violet-600 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 " onClick={() => handleCopy(referralCoupon.coupon_code, 0)}

                                        style={{
                                            backgroundColor: elSettings.copy_button_color || '#6D3AE6',
                                            color: elSettings.copy_button_text_color || '#fff',
                                        }}

                                        onMouseOver={(e) => {
                                            e.currentTarget.style.backgroundColor = elSettings.copy_button_hover_color || '#6D3AE6';
                                            e.currentTarget.style.color = elSettings.copy_button_text_hover_color || '#fff';
                                            const svgPaths = e.currentTarget.querySelectorAll('svg path');
                                            svgPaths.forEach(path => path.style.fill = elSettings.copy_button_svg_hover_color || '#fff');
                                        }}

                                        onMouseOut={(e) => {
                                            e.currentTarget.style.backgroundColor = elSettings.copy_button_color || '#6D3AE6';
                                            e.currentTarget.style.color = elSettings.copy_button_text_color || '#fff';
                                            const svgPaths = e.currentTarget.querySelectorAll('svg path');
                                            svgPaths.forEach(path => path.style.fill = elSettings.copy_button_svg_color || '#6D3AE6');
                                        }}

                                    >
                                        <span className="icon">
                                            <svg xmlns="http://www.w3.org/2000/svg" width="11" height="11" viewBox="0 0 11 11" fill="none">
                                                <path fillRule="evenodd" clipRule="evenodd" d="M6.90767 0.9375H2.6875L2.68602 0.937502C2.22271 0.938872 1.77876 1.12353 1.45114 1.45114C1.12353 1.77876 0.938869 2.22271 0.9375 2.68602V6.90625L0.937502 6.90767C0.938702 7.32961 1.10685 7.73393 1.40521 8.03229C1.69671 8.32379 2.08936 8.491 2.50077 8.49965C2.52742 9.36731 3.23916 10.0625 4.11328 10.0625H8.44922C9.34021 10.0625 10.0625 9.34021 10.0625 8.44922V4.11328C10.0625 3.23916 9.36731 2.52742 8.49965 2.50077C8.491 2.08936 8.32379 1.69671 8.03229 1.40521C7.73393 1.10685 7.32961 0.938702 6.90767 0.9375ZM7.99193 3.5C7.99094 3.5 7.98994 3.5 7.98894 3.5H4.11328C3.77458 3.5 3.5 3.77458 3.5 4.11328V8V8.44922C3.5 8.78792 3.77458 9.0625 4.11328 9.0625H8.44922C8.78792 9.0625 9.0625 8.78792 9.0625 8.44922V4.11328C9.0625 3.77458 8.78792 3.5 8.44922 3.5H7.99193ZM2.5 7.49901V4.11328C2.5 3.22229 3.22229 2.5 4.11328 2.5H7.49901C7.49061 2.35421 7.42898 2.21611 7.32518 2.11232C7.21381 2.00094 7.06293 1.93811 6.90543 1.9375H2.68833C2.48944 1.93826 2.2989 2.0176 2.15825 2.15825C2.0176 2.2989 1.93826 2.48944 1.9375 2.68833V6.90543C1.93811 7.06293 2.00094 7.21381 2.11232 7.32518C2.21611 7.42898 2.35421 7.49061 2.5 7.49901Z" fill={elSettings.copy_button_svg_color || '#6d3ae6'} />
                                            </svg>
                                        </span>
                                        <span >
                                            {copiedItemIndex === 0 ? translate('btn_copied') : translate('Copy')}
                                        </span>
                                    </button>

                                    {settings.enableReferralSocialSharing && (<button onClick={() => toggleReferralShareModal('general')} className="ecre-w-20 ecre-group ecre-px-2 ecre-py-[5px] ecre-bg-[#E7DDF4] 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 "
                                        style={{
                                            backgroundColor: elSettings.share_button_color || '#6D3AE6',
                                            color: elSettings.share_button_text_color || '#fff',
                                        }}

                                        onMouseOver={(e) => {
                                            e.currentTarget.style.backgroundColor = elSettings.share_button_hover_color || '#5023BB';
                                            e.currentTarget.style.color = elSettings.share_button_text_hover_color || '#fff';
                                            const svgPaths = e.currentTarget.querySelectorAll('svg path');
                                            svgPaths.forEach(path => path.style.fill = elSettings.share_button_svg_hover_color || '#452d7e');
                                        }}

                                        onMouseOut={(e) => {
                                            e.currentTarget.style.backgroundColor = elSettings.share_button_color || '#6D3AE6';
                                            e.currentTarget.style.color = elSettings.share_button_text_color || '#fff';
                                            const svgPaths = e.currentTarget.querySelectorAll('svg path');
                                            svgPaths.forEach(path => path.style.fill = elSettings.share_button_svg_color || '#452d7e');
                                        }}

                                    >
                                        <span className="icon">
                                            <svg xmlns="http://www.w3.org/2000/svg" width="12" height="11" viewBox="0 0 12 11" fill="none">
                                                <path className=" ecre-transition group-hover:ecre-fill-white" d="M8.02116 7.52714L11.2333 4.36785L11.274 4.32142C11.3343 4.24049 11.3634 4.14053 11.3559 4.03989C11.3484 3.93926 11.3049 3.8447 11.2333 3.77356L8.02116 0.615701L7.97687 0.577844C7.71973 0.384986 7.34116 0.570701 7.34116 0.912844V2.43427L7.18044 2.44499C4.63544 2.64642 3.14472 4.25713 2.78901 7.17857C2.7433 7.55357 3.1733 7.78857 3.45187 7.54C4.47401 6.62714 5.53044 6.05999 6.62687 5.83285C6.80259 5.79642 6.97902 5.76857 7.15687 5.74928L7.34116 5.73285V7.23L7.34473 7.28857C7.38759 7.61214 7.77973 7.76428 8.02116 7.52714ZM7.23259 3.15713L8.05545 3.10213V1.64999L10.5169 4.06999L8.05545 6.49142V4.95071L7.08687 5.03785H7.08116C5.86473 5.16856 4.71687 5.65571 3.6333 6.46785C3.84615 5.51142 4.20973 4.79214 4.68758 4.27713C5.28044 3.63785 6.10901 3.24713 7.23259 3.15713ZM2.42829 1.21427C1.95469 1.21427 1.50049 1.40241 1.1656 1.7373C0.830716 2.07218 0.642578 2.52639 0.642578 2.99999V8.71428C0.642578 9.18788 0.830716 9.64209 1.1656 9.97698C1.50049 10.3119 1.95469 10.5 2.42829 10.5H8.14259C8.61619 10.5 9.07039 10.3119 9.40528 9.97698C9.74017 9.64209 9.9283 9.18788 9.9283 8.71428V8C9.9283 7.90528 9.89068 7.81444 9.8237 7.74746C9.75672 7.68048 9.66588 7.64285 9.57116 7.64285C9.47644 7.64285 9.3856 7.68048 9.31862 7.74746C9.25165 7.81444 9.21402 7.90528 9.21402 8V8.71428C9.21402 8.99844 9.10114 9.27097 8.9002 9.4719C8.69927 9.67283 8.42675 9.78571 8.14259 9.78571H2.42829C2.14413 9.78571 1.87161 9.67283 1.67068 9.4719C1.46975 9.27097 1.35686 8.99844 1.35686 8.71428V2.99999C1.35686 2.71583 1.46975 2.44331 1.67068 2.24237C1.87161 2.04144 2.14413 1.92856 2.42829 1.92856H4.57115C4.66588 1.92856 4.75672 1.89093 4.82369 1.82395C4.89067 1.75698 4.9283 1.66614 4.9283 1.57142C4.9283 1.4767 4.89067 1.38586 4.82369 1.31888C4.75672 1.2519 4.66588 1.21427 4.57115 1.21427H2.42829Z" fill={elSettings.share_button_svg_color || '#452d7e'} />
                                            </svg>
                                        </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_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-box-border ecre-min-w-[250px] 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-w-full !ecre-rounded-lg !ecre-border !ecre-border-solid !ecre-border-[#E7DDF4] focus:!ecre-border-solid ${isPro && 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 ${isPro && 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={isPro && 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 ${isPro && settings.enableReferralLimit && referralCoupon.is_monthly_limit_reached ? 'ecre-opacity-50 ecre-cursor-not-allowed' : ''}`}  onClick={() => toggleReferralShareModal('refLink')} disabled={isPro && 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>

                    </>
                ) : (
                    <div className="ecre-mt-6">
                        <div className="icon ecre-flex ecre-justify-center ecre-mb-4">
                            {ecreIcons.noOrder}
                        </div>
                        <div className="ecre-text-[#5e656a] ecre-text-xs ecre-font-normal ecre-leading-[18px]">
                            <p className='ecre-text-center'>{settings.noOrderMessageToReferrer}</p>
                        </div>
                    </div>
                )
            ) : (
                <div>
                    <h3 className="ecre-text-neutral-950 ecre-text-[35px] !ecre-mt-0 ecre-font-medium ecre-mb-2">{translate('refer_and_win_exciting_rewards')}</h3>
                    <p className="ecre-text-[#686977] ecre-mb-5 ecre-text-xs ecre-font-normal"> {translate('create_account_get_referral_code')}</p>
                    <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-leading-[15px] 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>
            )}

            {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 ecre-border-solid 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 ReferralCardWidget;
