import React, { useState, useContext } 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 ReferralCard() {
    const { isPro, loadingSettings, loadingReferralCoupon, settings, referralCoupon, handleCopy, copiedItemIndex, handleToggleReferralShareModal, isReferralShareModal, socialMediaComponents, socialMediaComponentsForRefLink, default_settings,referralDiscountType, rewardlDiscountType, filteredSocialMediaOptions} = useContext(FrontendContext);

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

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


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

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

    return (
        <>
            <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">

                {(settings.canRefferOthers && ecreFrontend.has_orders) || !settings.canRefferOthers ? (
                    <>
                        <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-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('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-4">
                            <button
                                className={`ecre-w-20 ecre-group ecre-px-2 ecre-py-[5px] 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-[5px] 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' : ''}`}
                                    disabled={isPro && 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-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 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>{settings.noOrderMessageToReferrer}</p></div>
                    </div>
                )}

            </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]">
                                {filteredSocialMediaOptions.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 ReferralCard;
