import React, { useContext, useState, useEffect } from 'react';
import Tooltip from '../../../components/core/Tooltip';
import Select, { components } from 'react-select';
import Modal from '../../../components/core/Modal';
import { SettingsContext } from '../../App/SettingsContext';
import Switcher from '../fields/Switcher';
import Input from '../fields/Input';
import TextArea from '../fields/TextArea';
import EereSelect from '../fields/EereSelect';
import Header from '../Header';
import ecreIcons from '../../../components/core/icons';
import ImageUploader from '../fields/ImageUploader';
import EcreSocialSelect from '../fields/EcreSocialSelect';
import { translate } from '../../../Helper';
import EcreSelectPro from '../fields/EcreSelectPro';
import Loader from '../../../components/core/Loader';

function ReferralTab() {
    const {
        isOpen, handleToggleModal,
        referralCouponTypeOptions, referralFloatingWidgetOptions,
        woocommerceProductOptions, woocommerceProductCategoryOptions,
        socialMediaOptions, CustomOption, formData, handleInputChange, handleSelectChange, handleImageUpload, handleSocialSelectChange, handleReset, hasChanges, currency, pagesOptions, isPro, CouponTypeProOption, SubscriptionProOption, loading, initialFormData
    } = useContext(SettingsContext);

    // Add a state to track if everything is ready to render
    const [isSelectReady, setIsSelectReady] = useState(false);

    // Subscription modal state — lives here so it survives dropdown unmounting
    const [isSubscriptionModalOpen, setIsSubscriptionModalOpen] = useState(false);
    const handleToggleSubscriptionModal = () => setIsSubscriptionModalOpen(prev => !prev);

    // Define the effective referral coupon type
    const getEffectiveReferralCouponType = () => {
        return isPro
            ? formData.referralCouponType.value
            : (['sign_up_fee', 'sign_up_fee_percent', 'recurring_fee', 'recurring_percent'].includes(formData.referralCouponType.value)
                ? initialFormData.referralCouponType.value
                : formData.referralCouponType.value);
    };

    const effectiveReferralCouponType = getEffectiveReferralCouponType();

    // Use useEffect to set ready state after the initial render
    useEffect(() => {
        if (formData && formData.referralCouponType && referralCouponTypeOptions && referralCouponTypeOptions.length > 0) {
            setIsSelectReady(true);
        }
    }, [formData, formData.referralCouponType, referralCouponTypeOptions]);


    // Return loading until everything is ready
    if (loading) {
        return (
            <div className="referral-settings">
                <Header title={translate('referral_settings_title')} subtitle={translate('referral_settings_subtitle')} />
                <Loader />
            </div>
        );
    }

    // Return loading until everything is ready
    if (!isSelectReady || !effectiveReferralCouponType) {
        return (
            <div className="referral-settings">
                <Header title={translate('referral_settings_title')} subtitle={translate('referral_settings_subtitle')} />
            </div>
        );
    }


    return (
        <>
            <div className="referral-settings">
                <Header title={translate('referral_settings_title')} subtitle={translate('referral_settings_subtitle')} />

                <div className="referral-program">
                    <div className="referral-program__enable-field ecre-mb-8">
                        <Switcher
                            id="enable-referral-program"
                            checked={formData.enableReferralProgram}
                            onChange={handleInputChange('enableReferralProgram')}
                            label={translate('enable_referral_program_label')}
                            tooltip={translate('enable_referral_program_tooltip')}
                        />
                        <p className="ecre-text-gray-500 ecre-text-xs ecre-font-normal"> {translate('enable_referral_program_desc')}</p>
                    </div>

                    <div className={`referral-program__enable-content ${!formData.enableReferralProgram ? 'ecre-opacity-40 ecre-pointer-events-none' : ''}`}>
                        <div className="form-group ecre-mb-8">
                            <Switcher
                                id="enable-referral-link"
                                checked={formData.enableReferralLink}
                                onChange={handleInputChange('enableReferralLink')}
                                label={translate('enable_referral_link_label')}
                                tooltip={translate('enable_referral_link_tooltip')}
                                />

                        </div>

                        <div className="form-group ecre-mb-8">
                            <EcreSelectPro
                                id="referral_coupon_type"
                                label={translate('referral_coupon_type_label')}
                                options={referralCouponTypeOptions}
                                value={
                                    isPro
                                        ? formData.referralCouponType.value // Use whatever is selected when Pro
                                        : (['sign_up_fee', 'sign_up_fee_percent', 'recurring_fee', 'recurring_percent'].includes(formData.referralCouponType.value)
                                            ? initialFormData.referralCouponType.value
                                            : formData.referralCouponType.value)
                                }
                                onChange={handleSelectChange('referralCouponType')}
                                width="320"
                                classNamePrefix="echorewards-select"
                                isSearchable={false}
                                placeholder={translate('referral_coupon_type_placeholder')}
                                tooltip={translate('referral_coupon_type_tooltip')}
                                components={{ Option: !isPro ? CouponTypeProOption : SubscriptionProOption }}
                                isPro={isPro}
                                isOptionDisabled={(option) => ['sign_up_fee', 'sign_up_fee_percent', 'recurring_fee', 'recurring_percent'].includes(option.value)}
                                onSubscriptionClick={handleToggleSubscriptionModal}
                            />
                        </div>

                        <div className="form-group ecre-mb-8">
                            {(effectiveReferralCouponType === 'sign_up_fee' || effectiveReferralCouponType === 'sign_up_fee_percent') && (
                                <TextArea
                                    id="referral_signup_coupon_note"
                                    label={translate('coupon_note_for_customers_label')}
                                    tooltip={translate('subscription_based_products_tooltip')}
                                    rows={2}
                                    cols={30}
                                    width="430px"
                                    value={formData.referralSignupCouponNote}
                                    onChange={handleInputChange('referralSignupCouponNote')}
                                    marginTop='ecre-mt-2'
                                    isPro={isPro}
                                />
                            )}

                            {(effectiveReferralCouponType === 'recurring_fee' || effectiveReferralCouponType === 'recurring_percent') && (
                                <TextArea
                                    id="referral_recurring_coupon_note"
                                    label={translate('coupon_note_for_customers_label')}
                                    tooltip={translate('subscription_based_products_tooltip')}
                                    rows={2}
                                    cols={30}
                                    width="430px"
                                    value={formData.referralRecurringCouponNote}
                                    onChange={handleInputChange('referralRecurringCouponNote')}
                                    marginTop='ecre-mt-2'
                                    isPro={isPro}
                                />
                            )}
                        </div>

                        <div className="form-group ecre-mb-8">
                            <Input
                                id="discount-percent"
                                label={`${translate('discount_capital')} ${effectiveReferralCouponType === 'sign_up_fee'
                                    ? translate('sign_up_fee')
                                    : effectiveReferralCouponType === 'sign_up_fee_percent'
                                        ? translate('sign_up_fee')
                                        : effectiveReferralCouponType === 'recurring_fee'
                                            ? translate('recurring_fee')
                                            : effectiveReferralCouponType === 'recurring_percent'
                                                ? translate('recurring_fee')
                                                : translate(effectiveReferralCouponType)
                                    } ${translate('amount_lower')} ${['sign_up_fee_percent', 'recurring_percent', 'percent'].includes(effectiveReferralCouponType)
                                        ? '(%)'
                                        : `(${currency})`
                                    }`}
                                tooltip={translate('discount_percent_tooltip')}
                                type="number"
                                value={formData.referralDiscount}
                                onChange={handleInputChange('referralDiscount')}
                            />
                        </div>

                        {effectiveReferralCouponType === 'percent' && (
                            <div className="form-group ecre-mb-8">
                                <Input
                                    id="referral_discount_capping"
                                    label={`${translate('discount_capping_label')} (${currency})`}
                                    tooltip={translate('discount_capping_tooltip')}
                                    type="number"
                                    value={formData.referralDiscountCapping}
                                    onChange={handleInputChange('referralDiscountCapping')}
                                />
                            </div>
                        )}

                        {(!['reward_point', 'percent', 'fixed', 'sign_up_fee', 'sign_up_fee_percent'].includes(effectiveReferralCouponType)) && (
                            <div className="form-group ecre-mb-8">
                                <Switcher
                                    id="enable_limit_coupon_usage_subscription"
                                    checked={isPro ? formData.enableReferralLimitSubscriptionCoupon : false}
                                    onChange={handleInputChange('enableReferralLimitSubscriptionCoupon')}
                                    label={translate('limit_the_coupon_usage_for_subscription_payments')}
                                    tooltip={translate('limit_the_coupon_usage_for_subscription_payments_tooltip')}
                                    marginTop='ecre-mt-2'
                                    isPro={isPro}
                                />

                                {formData.enableReferralLimitSubscriptionCoupon && isPro && (
                                    <Input
                                        id="referral_limit_subscription_coupon"
                                        label={`${translate('number_of_payments_coupon_is_valid_for')} (${currency})`}
                                        type="number"
                                        value={formData.referralLimitSubscriptionCoupon}
                                        onChange={handleInputChange('referralLimitSubscriptionCoupon')}
                                        marginTop='ecre-mt-2'
                                        isPro={isPro}
                                    />
                                )}
                            </div>
                        )}

                        <div className="form-group ecre-mb-8">
                            <Switcher
                                id="can_reffer_others"
                                checked={formData.canRefferOthers}
                                onChange={handleInputChange('canRefferOthers')}
                                label={translate('referrer_order_required_label')}
                                tooltip={translate('referrer_order_required_tooltip')}
                            />

                            <TextArea
                                id="referral_no_order_message"
                                label={translate('no_order_message_label')}
                                rows={4}
                                cols={30}
                                width="430px"
                                value={isPro ? formData.noOrderMessageToReferrer : initialFormData.noOrderMessageToReferrer}
                                onChange={handleInputChange('noOrderMessageToReferrer')}
                                marginTop='ecre-mt-2'
                                isPro={isPro}
                            />
                        </div>

                        <div className="form-group ecre-mb-8">
                            <Input
                                id="referral_menu_name"
                                label={translate('referral_menu_name_label')}
                                tooltip={translate('referral_menu_name_tooltip')}
                                type="text"
                                width='514'
                                value={formData.referralMenuName}
                                onChange={handleInputChange('referralMenuName')}
                            />
                        </div>

                        <div className="form-group ecre-mb-6">
                            <div className="ecre-flex ecre-flex-wrap ecre-gap-4 ecre-mb-2">
                                <ImageUploader
                                    imageUrl={formData.referralMenuIcon}
                                    setImageUrl={(url) => handleImageUpload('referralMenuIcon', url)}
                                    label={translate('referral_menu_icon_label')}
                                    uploaderTitle={translate('choice_menu_icon')}
                                    uploaderBtnText={translate('upload_icon')}
                                    tooltip={translate('referral_menu_icon_tooltip')}
                                />
                            </div>

                            <Switcher
                                id="hide_referral_menu_icon"
                                checked={isPro ? formData.hideReferralMenuIcon : false}
                                onChange={handleInputChange('hideReferralMenuIcon')}
                                label={translate('hide_referral_menu_icon_label')}
                                isPro={isPro}
                                tooltip={translate('enable_hide_referral_menu_icon')}
                            />
                        </div>

                        <div className="form-group ecre-mb-6">
                            <Switcher
                                id="is_user_loggedin"
                                checked={isPro ? formData.is_user_loggedin : false}
                                onChange={handleInputChange('is_user_loggedin')}
                                label={translate('customer_needs_to_logged_in')}
                                tooltip={translate('customer_needs_to_logged_in_tooltip')}
                                isPro={isPro}
                            />
                        </div>

                        <div className="form-group ecre-mb-6">
                            <Switcher
                                id="can_use_referral_coupon"
                                checked={isPro ? formData.canUseReferralCoupon : false}
                                onChange={handleInputChange('canUseReferralCoupon')}
                                label={translate('can_use_referral_coupon_label')}
                                tooltip={translate('can_use_referral_coupon_tooltip')}
                                isPro={isPro}
                            />
                        </div>

                        <div className="form-group ecre-mb-8">
                            <Switcher
                                id="enable_referral_limit"
                                checked={isPro ? formData.enableReferralLimit : false}
                                onChange={handleInputChange('enableReferralLimit')}
                                label={translate('enable_referral_limit_label')}
                                tooltip={translate('enable_referral_limit_tooltip')}
                                isPro={isPro}
                            />

                            {formData.enableReferralLimit && isPro && (
                                <Input
                                    id="referral_monthly_limit"
                                    label={translate('monthly_referral_limit_label')}
                                    tooltip={translate('monthly_referral_limit_tooltip')}
                                    type="number"
                                    value={formData.referralMonthlyLimit}
                                    onChange={handleInputChange('referralMonthlyLimit')}
                                    marginTop='ecre-mt-2'
                                    isPro={isPro}
                                />
                            )}
                        </div>

                        <div className="form-group ecre-mb-8">
                            <Switcher
                                id="enable_tab_on_wooCommerce_product"
                                checked={formData.enableTabOnWooCommerceProduct}
                                onChange={handleInputChange('enableTabOnWooCommerceProduct')}
                                label={translate('enable_tab_on_wc_product_label')}
                                tooltip={translate('enable_tab_on_wc_product_tooltip')}
                            />
                        </div>

                        <div className="form-group ecre-mb-8">
                            <Input
                                id="referral_minimum_purchase_amount"
                                label={`${translate('min_purchase_amount_label')} (${currency})`}
                                tooltip={translate('min_purchase_amount_tooltip')}
                                type="number"
                                value={formData.referralMinimumPurchaseAmount}
                                onChange={handleInputChange('referralMinimumPurchaseAmount')}
                            />
                        </div>

                        <div className="form-group ecre-mb-8">
                            <Input
                                id="referral_coupon_prefix"
                                label={translate('referral_coupon_prefix_label')}
                                tooltip={translate('referral_coupon_prefix_tooltip')}
                                type="text"
                                value={isPro ? formData.referralCouponPrefix : initialFormData.referralCouponPrefix}
                                onChange={handleInputChange('referralCouponPrefix')}
                                isPro={isPro}
                            />
                        </div>

                        <div className="form-group ecre-mb-8">
                            <Switcher
                                id="enable_referral_floating_widget"
                                checked={isPro ? formData.enableReferralFloatingWidget : false}
                                onChange={handleInputChange('enableReferralFloatingWidget')}
                                label={translate('enable_referral_floating_widget_label')}
                                tooltip={translate('enable_referral_floating_widget_tooltip')}
                                isPro={isPro}
                            />

                            {formData.enableReferralFloatingWidget && isPro && (
                                <>
                                    <EereSelect
                                        id="widget-position"
                                        label={translate('select_widget_position_label')}
                                        options={referralFloatingWidgetOptions}
                                        value={formData.referralWidgetPosition.value}
                                        onChange={handleSelectChange('referralWidgetPosition')}
                                        width="320"
                                        classNamePrefix="echorewards-select"
                                        isSearchable={false}
                                        placeholder={translate('select_possition')}
                                        marginTop='ecre-mt-2'
                                        isPro={isPro}
                                    />

                                    <EereSelect
                                        id="ecre_pagesfor_folating_widgets"
                                        label={translate('widget_pages_label')}
                                        options={pagesOptions}
                                        value={formData.pagesForWidgets}
                                        onChange={handleSelectChange('pagesForWidgets')}
                                        width="570"
                                        classNamePrefix="echorewards-select"
                                        isSearchable={true}
                                        placeholder={translate('enter_three_characters')}
                                        marginTop='ecre-mt-6'
                                        isMulti={true}
                                        tooltip={translate('widget_pages_tooltip')}
                                        isPro={isPro}
                                    />
                                </>
                            )}
                        </div>

                        <div className="form-group ecre-mb-8">
                            <EereSelect
                                id="referral_include_products"
                                label={translate('include_products_label')}
                                options={woocommerceProductOptions}
                                value={formData.referralIncludeProducts}
                                onChange={handleSelectChange('referralIncludeProducts')}
                                width="570"
                                classNamePrefix="echorewards-select"
                                isSearchable={true}
                                placeholder={translate('enter_three_characters')}
                                isMulti={true}
                                tooltip={translate('include_products_tooltip')}
                            />
                        </div>

                        <div className="form-group ecre-mb-8">
                            <EereSelect
                                id="referral_exclude_products"
                                label={translate('exclude_products_label')}
                                options={woocommerceProductOptions}
                                value={formData.referralExcludeProducts}
                                onChange={handleSelectChange('referralExcludeProducts')}
                                width="570"
                                classNamePrefix="echorewards-select"
                                isSearchable={true}
                                placeholder={translate('enter_three_characters')}
                                isMulti={true}
                                tooltip={translate('exclude_products_tooltip')}
                            />
                        </div>

                        <div className="form-group ecre-mb-8">
                            <EereSelect
                                id="referral_include_categories"
                                label={translate('include_categories_label')}
                                options={woocommerceProductCategoryOptions}
                                value={formData.referralIncludeCategories}
                                onChange={handleSelectChange('referralIncludeCategories')}
                                width="570"
                                classNamePrefix="echorewards-select"
                                isSearchable={true}
                                placeholder={translate('enter_three_characters')}
                                isMulti={true}
                                tooltip={translate('include_categories_tooltip')}
                            />
                        </div>

                        <div className="form-group ecre-mb-8">
                            <EereSelect
                                id="referral_exclude_categories"
                                label={translate('exclude_categories_label')}
                                options={woocommerceProductCategoryOptions}
                                value={formData.referralExcludeCategories}
                                onChange={handleSelectChange('referralExcludeCategories')}
                                width="570"
                                classNamePrefix="echorewards-select"
                                isSearchable={true}
                                placeholder={translate('enter_three_characters')}
                                isMulti={true}
                                tooltip={translate('exclude_categories_tooltip')}
                            />
                        </div>

                        <div className="form-group ecre-mb-8">
                            <Switcher
                                id="enable_referral_social_sharing"
                                checked={formData.enableReferralSocialSharing}
                                onChange={handleInputChange('enableReferralSocialSharing')}
                                label={translate('enable_social_sharing_label')}
                                tooltip={translate('enable_social_sharing_tooltip')}
                            />

                            {formData.enableReferralSocialSharing && (
                                <EcreSocialSelect
                                    id="referral_social_media_options"
                                    label={translate('select_social_media_label')}
                                    options={socialMediaOptions}
                                    components={{ Option: CustomOption }}
                                    value={
                                        isPro
                                            ? formData.socialMediaOptions // Use all selected options when Pro
                                            : formData.socialMediaOptions.filter(option =>
                                                ['Facebook', 'WhatsApp'].includes(option.value)
                                            )
                                    }
                                    onChange={handleSocialSelectChange}
                                    width="570"
                                    classNamePrefix="echorewards-select"
                                    isSearchable={false}
                                    placeholder={translate('select_social_media_placeholder')}
                                    isMulti={true}
                                    tooltip={translate('select_social_media_tooltip')}
                                    marginTop='ecre-mt-2'
                                    isPro={isPro}
                                    isOptionDisabled={(option) =>
                                        !isPro && !['Facebook', 'WhatsApp'].includes(option.value)
                                    }
                                />
                            )}
                        </div>
                    </div>
                </div>
            </div>

            {/* Subscription modal — rendered outside the dropdown so it survives unmounting */}
            <Modal openModal={isSubscriptionModalOpen} toggleModal={handleToggleSubscriptionModal}>
                {{
                    header: <h6 className="title ecre-text-gray-900 ecre-text-base ecre-font-semibold">{translate('subscription_plugin_not_active')}</h6>,
                    body: <p className="ecre-text-gray-900 ecre-text-sm ecre-font-normal">
                        {translate('this_feature_requires_wooCommerce_subscription')}&nbsp;&nbsp;{translate('please')}&nbsp;
                        <a href='https://woocommerce.com/products/woocommerce-subscriptions/' target='_blank' rel='noreferrer'>{translate('get_the_plugin_from_this_link')}</a>
                        &nbsp;{translate('and_activate_use_subscription_coupons')}
                    </p>,
                    footer: (
                        <div className="btn-box ecre-justify-end ecre-items-center ecre-gap-2 ecre-flex">
                            <button
                                onClick={handleToggleSubscriptionModal}
                                className="ecre-text-gray-900 ecre-cursor-pointer ecre-text-sm ecre-font-semibold ecre-px-4 ecre-py-2.5 ecre-transition ecre-bg-slate-100 ecre-rounded-lg ecre-border ecre-border-solid ecre-border-slate-100 hover:ecre-border-red-500 hover:ecre-bg-white hover:ecre-text-red-500"
                            >
                                {translate('cancel')}
                            </button>
                        </div>
                    )
                }}
            </Modal>
        </>
    );
}

export default ReferralTab;