import React, { useState, useMemo, useContext, useEffect } from 'react';
import { SettingsContext } from '../../App/SettingsContext';
import SelectPerPagination from '../fields/SelectPerPagination';
import SelectTimeFilter from '../fields/SelectTimeFilter';
import ecreIcons from '../../../components/core/icons';
import Pagination from '../Pagination';
import ReferralHistoryRow from './ReferralHistoryRow';
import Modal from '../../../components/core/Modal';
import Input from '../fields/Input';
import Switcher from '../fields/Switcher';
import EcreSelectPro from '../fields/EcreSelectPro';
import { useUserRewardSettings } from '../../hooks/useUserRewardSettings';
import { displayProPopup } from '../../../Helper';
import axios from 'axios';
import Tooltip from '../../../components/core/Tooltip';
import CustomizedPill from '../../../components/core/CustomizedPill';
import { translate } from '../../../Helper';

const ReferralHistory = () => {
    const {
        selectedReferrer,
        formData,
        referralCouponTypeOptions,
        CouponTypeProOption,
        SubscriptionProOption,
        isPro,
        initialFormData, currency
    } = useContext(SettingsContext);

    // ADD this hook
    const {
        userCustomSettings,
        hasCustomSettings,
        globalSettings,
        settingsLoading,
        fetchUserCustomSettings,
        saveUserCustomSettings,
        resetToDefaultSettings
    } = useUserRewardSettings(formData);

    const [loading, setLoading] = useState(true); // Start as true for initial load
    const [isPaginating, setIsPaginating] = useState(false); // Track pagination separately
    const [referrals, setReferrals] = useState([]);
    const [currentPage, setCurrentPage] = useState(1);
    const [itemsPerPage, setItemsPerPage] = useState(10);
    const [timeFilter, setTimeFilter] = useState('All Time');
    const isReferralCouponTypeDisabled = true;

    // Pagination info from server
    const [paginationInfo, setPaginationInfo] = useState({
        current_page: 1,
        per_page: 10,
        total_items: 0,
        total_pages: 0,
        has_more: false
    });

    // ADD - Modal states for Customize Referral Options
    const [isOpenReferralOptions, setIsOpenReferralOptions] = useState(false);
    const [isOpenResetModal, setIsOpenResetModal] = useState(false);

    // ADD - Custom referral settings form states  
    const [customReferralCouponType, setCustomReferralCouponType] = useState(null);
    const [customReferralDiscount, setCustomReferralDiscount] = useState('');
    const [referralDiscountCapping, setReferralDiscountCapping] = useState('');
    const [enableReferralLimit, setEnableReferralLimit] = useState(false);
    const [referralMonthlyLimit, setReferralMonthlyLimit] = useState('');
    const [referralMinimumPurchase, setReferralMinimumPurchase] = useState('');

    // Fetch referral history data
    const fetchReferralHistory = async (isInitial = false) => {
        if (!selectedReferrer || !selectedReferrer.user_id) {
            setLoading(false);
            return;
        }

        if (isInitial) {
            setLoading(true);
        } else {
            setIsPaginating(true);
        }

        try {
            const formData = new FormData();
            formData.append('action', 'ecre_fetch_referrer_history');
            formData.append('nonce', ecreAdmin.nonce);
            formData.append('referrer_user_id', selectedReferrer.user_id);
            formData.append('page', currentPage);
            formData.append('per_page', itemsPerPage);
            formData.append('time_filter', timeFilter);
            const response = await axios.post(ecreAdmin.ajaxurl, formData);

            if (response.data.success) {
                setReferrals(response.data.data.referrals);
                setPaginationInfo(response.data.data.pagination);
            } else {
                console.error('Failed to fetch referral history:', response.data.data);
            }
        } catch (error) {
            console.error('Error fetching referral history:', error);
        } finally {
            setLoading(false);
            setIsPaginating(false);
        }
    };

    // ADD - Edit referral handler
    const handleEditReferral = () => {
        setIsOpenReferralOptions(true);
    };

    // ADD - Modal toggle handler
    const handleReferralOptionsToggleModal = async () => {
        if (!isOpenReferralOptions) {
            await loadReferralSettings();
        }
        setIsOpenReferralOptions(!isOpenReferralOptions);
    };


    // REPLACE the existing loadReferralSettings function with this FIXED version
    const loadReferralSettings = async () => {
        if (!selectedReferrer || !selectedReferrer.user_id) return;

        const result = await fetchUserCustomSettings(selectedReferrer.user_id);

        if (result) {
            const referralCouponTypeObject = result.getEffectiveValue('referralCouponType', formData.referralCouponType);
            const referralDiscount = result.getEffectiveValue('referralDiscount', formData.referralDiscount || '');

            // Extract the value from the object (handle both object and string cases)
            const referralTypeValue = referralCouponTypeObject?.value || referralCouponTypeObject;

            // Find the matching option
            const referralTypeOption = referralCouponTypeOptions.find(
                option => option.value === referralTypeValue
            );


            // setCustomReferralCouponType(referralTypeOption || formData.referralCouponType);
            setCustomReferralDiscount(referralDiscount);
            setReferralDiscountCapping(result.getEffectiveValue('referralDiscountCapping', formData.referralDiscountCapping || ''));
            setEnableReferralLimit(result.getEffectiveValue('enableReferralLimit', formData.enableReferralLimit || false));
            setReferralMonthlyLimit(result.getEffectiveValue('referralMonthlyLimit', formData.referralMonthlyLimit || ''));
            setReferralMinimumPurchase(result.getEffectiveValue('referralMinimumPurchaseAmount', formData.referralMinimumPurchaseAmount || ''));
        } else {
            // Set global defaults when no custom settings exist
            setCustomReferralCouponType(formData.referralCouponType);
            setCustomReferralDiscount(formData.referralDiscount || '');
            setReferralDiscountCapping(formData.referralDiscountCapping || '');
            setEnableReferralLimit(formData.enableReferralLimit || false);
            setReferralMonthlyLimit(formData.referralMonthlyLimit || '');
            setReferralMinimumPurchase(formData.referralMinimumPurchaseAmount || '');
        }
    };

    // ADD - Get effective referral coupon type (similar to RewardCoupons.jsx)
    const getEffectiveReferralCouponType = () => {
        const currentReferralCouponType = customReferralCouponType || formData.referralCouponType;
        return isPro
            ? currentReferralCouponType?.value
            : (['sign_up_fee', 'sign_up_fee_percent', 'recurring_fee', 'recurring_percent'].includes(currentReferralCouponType?.value)
                ? initialFormData.referralCouponType?.value
                : currentReferralCouponType?.value);
    };

    // REPLACE your existing getReferralText function with this FIXED version
    const getReferralText = () => {
        // Use SAVED settings - prioritize custom settings if they exist
        const savedCouponType = hasCustomSettings ? userCustomSettings?.referralCouponType : formData.referralCouponType;

        const savedDiscount = hasCustomSettings
            ? userCustomSettings?.referralDiscount    // Saved custom discount
            : formData.referralDiscount;              // Global discount

        // Extract the actual value from the coupon type object/array
        const effectiveReferralCouponType = (() => {
            let couponTypeValue;

            if (hasCustomSettings && savedCouponType) {
                // Handle array format from database: {"value":"percent","label":"Percentage"}
                couponTypeValue = savedCouponType.value || savedCouponType;
            } else {
                // Handle global format (could be object or string)
                couponTypeValue = formData.referralCouponType?.value || formData.referralCouponType;
            }

            // Apply Pro restrictions
            return isPro
                ? couponTypeValue
                : (['sign_up_fee', 'sign_up_fee_percent', 'recurring_fee', 'recurring_percent'].includes(couponTypeValue)
                    ? initialFormData.referralCouponType?.value  // Fall back to default for non-pro
                    : couponTypeValue);
        })();

        // Use saved discount amount, not form state
        const referralAmount = savedDiscount || 10;

        let referralText = '';

        switch (effectiveReferralCouponType) {
            case 'percent':
                referralText = `${translate('referral_text_percentage_coupon')} ${referralAmount}% ${translate('referral_text_off_to_new_customers')}`;
                break;
            case 'fixed':
                referralText = `${translate('referral_text_fixed_coupon')} ${currency}${referralAmount} ${translate('referral_text_off_to_new_customers')}`;
                break;
            case 'sign_up_fee':
                referralText = `${translate('referral_text_sign_up_fee_coupon')} ${currency}${referralAmount} ${translate('referral_text_off_sign_up_fee')}`;
                break;
            case 'sign_up_fee_percent':
                referralText = `${translate('referral_text_sign_up_fee_coupon')} ${referralAmount}% ${translate('referral_text_off_sign_up_fee')}`;
                break;
            case 'recurring_fee':
                referralText = `${translate('referral_text_recurring_fee_coupon')} ${currency}${referralAmount} ${translate('referral_text_off_recurring_payments')}`;
                break;
            case 'recurring_percent':
                referralText = `${translate('referral_text_recurring_fee_coupon')} ${referralAmount}% ${translate('referral_text_off_recurring_payments')}`;
                break;
            default:
                referralText = `${translate('referral_text_percentage_coupon')} ${referralAmount}% ${translate('referral_text_off_to_new_customers')}`;
        }

        return referralText;
    };

    // REPLACE the existing handleSaveReferralSettings function with this FIXED version
    const handleSaveReferralSettings = async () => {
        if (!selectedReferrer || !selectedReferrer.user_id) return;

        const settings = {
            //referralCouponType: customReferralCouponType ? customReferralCouponType : formData.referralCouponType,
            referralDiscount: customReferralDiscount || formData.referralDiscount || 0,
            referralDiscountCapping: referralDiscountCapping || formData.referralDiscountCapping || 0,
            enableReferralLimit: enableReferralLimit !== undefined ? enableReferralLimit : formData.enableReferralLimit,
            referralMonthlyLimit: referralMonthlyLimit || formData.referralMonthlyLimit || 0,
            referralMinimumPurchaseAmount: referralMinimumPurchase || formData.referralMinimumPurchaseAmount || 0,

            // Add the special flag for referral coupon update
            referral_coupon_update: true,

            // Include selectedReferrer data with coupon info
            coupon_code: selectedReferrer.referral_coupon_code,
            coupon_id: selectedReferrer.referral_coupon_id,
        };

        try {
            const result = await saveUserCustomSettings(selectedReferrer.user_id, settings);
            if (result.success) {
                setIsOpenReferralOptions(false);
                // Refresh the referral settings to show updated values
                await loadReferralSettings();
            } else {
                console.error('Failed to save referral settings:', result.error);
            }
        } catch (error) {
            console.error('Error saving referral settings:', error);
        }
    };

    // ADD - Confirm reset function
    const handleConfirmReset = async () => {
        try {
            if (!selectedReferrer?.user_id) return;

            const result = await resetToDefaultSettings(selectedReferrer.user_id);

            if (result.success) {
                // Reset local form state to global defaults
                setCustomReferralCouponType(formData.referralCouponType);
                setCustomReferralDiscount(formData.referralDiscount || '');
                setReferralDiscountCapping(formData.referralDiscountCapping || '');
                setEnableReferralLimit(formData.enableReferralLimit || false);
                setReferralMonthlyLimit(formData.referralMonthlyLimit || '');
                setReferralMinimumPurchase(formData.referralMinimumPurchaseAmount || '');

                // Close both modals
                setIsOpenResetModal(false);
                setIsOpenReferralOptions(false);

                // Reload settings to refresh the state
                await loadReferralSettings();
            } else {
                console.error('Reset failed:', result);
            }
        } catch (error) {
            console.error('Error resetting referral settings:', error);
        }
    };

    // Fetch data when component mounts or filters change
    useEffect(() => {
        fetchReferralHistory();
        // Load referral settings when selectedReferrer changes
        if (selectedReferrer && selectedReferrer.user_id) {
            loadReferralSettings();
        }
    }, [selectedReferrer, currentPage, itemsPerPage, timeFilter]);

    // ADD - Refresh settings when page becomes visible (fixes caching issue with retry)
    useEffect(() => {
        let retryTimeout;

        const handleVisibilityChange = () => {
            if (!document.hidden && selectedReferrer && selectedReferrer.user_id) {

                // First attempt - immediate
                loadReferralSettings();

                // Second attempt - after 1 second (catches most syncs)
                retryTimeout = setTimeout(() => {
                    loadReferralSettings();
                }, 1000);

                // Third attempt - after 2 seconds (catches slow syncs)
                setTimeout(() => {
                    loadReferralSettings();
                }, 2000);
            }
        };

        document.addEventListener('visibilitychange', handleVisibilityChange);

        return () => {
            document.removeEventListener('visibilitychange', handleVisibilityChange);
            if (retryTimeout) clearTimeout(retryTimeout);
        };
    }, [selectedReferrer]);

    // Event Handlers
    const handlePageChange = (page) => {
        setCurrentPage(page);
    };

    const handleItemsPerPageChange = (newItemsPerPage) => {
        setItemsPerPage(newItemsPerPage);
        setCurrentPage(1);
    };

    // Clear active filters - RESTORED from old file
    const clearFilters = () => {
        setTimeFilter('All Time');
        setCurrentPage(1);
    };

    const hasActiveFilters = timeFilter !== 'All Time';

    return (
        <div className="referrer-details__referral-history">
            <div className="ecre-p-4 ecre-mb-6 ecre-bg-white ecre-rounded-lg ecre-border ecre-border-gray-200 ecre-flex ecre-justify-between ecre-items-center ecre-gap-3">
                <div className="ecre-text-sm ecre-text-gray-600 ecre-font-medium">{translate('referral_history_referral')}
                    {selectedReferrer?.referral_coupon_code && (
                        <span className="ecre-text-gray-900 ecre-font-bold ecre-ml-2">
                            {selectedReferrer.referral_coupon_code.toUpperCase()}
                        </span>
                    )}
                    <span className="ecre-text-gray-900 ecre-font-normal"> ({getReferralText()})</span>

                    {hasCustomSettings && (
                        <CustomizedPill />
                    )}
                </div>
                <div onClick={!isPro ? displayProPopup : handleEditReferral} className={`${!isPro ? 'ecre-opacity-50' : ''} ecre-text-[#3b71ca] ecre-ml-auto ecre-text-sm ecre-font-medium ecre-cursor-pointer ecre-transition hover:ecre-text-[#6a40d5]`}>{translate('referral_history_edit')}</div>
                {!isPro && (
                    <button className='ecre-px-1.5 btn-prolock !ecre-ml-0 ecre-border-0 ecre-inline-flex ecre-items-center ecre-pt-[3px] ecre-pb-[4px] ecre-bg-[#fee8fd] ecre-rounded-[26px] ecre-text-[#4d1c4b] ecre-text-sm ecre-font-normal' onClick={displayProPopup}>
                        <span className="icon-wrap">
                            <svg xmlns="http://www.w3.org/2000/svg" width="13" height="11" viewBox="0 0 13 11" fill="none">
                                <path d="M0.806113 7.65309C0.542977 5.94268 0.279841 4.23232 0.0167049 2.52191C-0.0416496 2.14276 0.389758 1.88417 0.696628 2.11434C1.51645 2.7292 2.33622 3.34402 3.15604 3.95889C3.42597 4.16133 3.81053 4.09545 3.99766 3.81471L6.04517 0.743421C6.26154 0.41886 6.73842 0.41886 6.95479 0.743421L9.0023 3.81471C9.18944 4.09545 9.574 4.16129 9.84392 3.95889C10.6637 3.34402 11.4835 2.7292 12.3033 2.11434C12.6102 1.88417 13.0416 2.14276 12.9833 2.52191C12.7202 4.23232 12.457 5.94268 12.1939 7.65309H0.806113Z" fill="#F748F0" />
                                <path d="M11.6001 10.5H1.39974C1.07185 10.5 0.80603 10.2342 0.80603 9.90627V8.60205H12.1938V9.90627C12.1938 10.2342 11.9279 10.5 11.6001 10.5Z" fill="#F748F0" />
                            </svg>
                        </span>
                        <span className="text">{translate('referral_history_upgrade')}</span>
                    </button>
                )}
            </div>

            <div className="filterbar ecre-mb-2">
                <div className="filterbar ecre-flex ecre-flex-wrap ecre-justify-between ecre-items-center ecre-gap-2">
                    <SelectPerPagination
                        startIndex={((currentPage - 1) * itemsPerPage) + 1}
                        endIndex={Math.min(currentPage * itemsPerPage, paginationInfo.total_items)}
                        totalItems={paginationInfo.total_items}
                        itemsPerPage={itemsPerPage}
                        onItemsPerPageChange={handleItemsPerPageChange}
                    />

                    <SelectTimeFilter
                        timeFilter={timeFilter}
                        onTimeFilterChange={setTimeFilter}
                    />
                </div>

                {hasActiveFilters && (
                    <div className="ecre-flex">
                        <div
                            onClick={() => clearFilters()}
                            className="ecre-cursor-pointer ecre-inline-flex ecre-gap-1 ecre-text-[#6a40d5] ecre-text-xs ecre-font-medium ecre-mt-2 ecre-ml-auto">
                            {translate('referral_history_clear_filter')}
                            <span className="icon ecre-ml-1">{ecreIcons.circleClose}</span>
                        </div>
                    </div>
                )}
            </div>

            {loading ? (
                <div className="ecre-text-center ecre-py-8">{translate('referral_history_loading')}</div>
            ) : (
                <>
                    <div className="ecre-overflow-x-auto">
                        <table className="referrer-table ecre-w-full ecre-border-spacing-[0px]">
                            <thead className="ecre-bg-[#F3F4F6]">
                                <tr>
                                    <th className="ecre-px-5 ecre-py-4 ecre-text-left ecre-text-sm ecre-font-normal ecre-text-gray-600">
                                        {translate('referral_history_referred_user')}
                                    </th>
                                    <th className="ecre-px-5 ecre-py-4 ecre-text-left ecre-text-sm ecre-font-normal ecre-text-gray-600">
                                        {translate('referral_history_order_value')}
                                    </th>
                                    <th className="ecre-px-5 ecre-py-4 ecre-text-left ecre-text-sm ecre-font-normal ecre-text-gray-600">
                                        {translate('referral_history_date')}
                                    </th>
                                    <th className="ecre-px-5 ecre-py-4 ecre-text-left ecre-text-sm ecre-font-normal ecre-text-gray-600">
                                        {translate('referral_history_referral_status')}
                                    </th>
                                    <th className="ecre-px-5 ecre-py-4 ecre-text-left ecre-text-sm ecre-font-normal ecre-text-gray-600">
                                        {translate('referral_history_actions')}
                                    </th>
                                </tr>
                            </thead>
                            <tbody className="ecre-bg-white ecre-divide-y ecre-divide-gray-200">
                                {referrals && referrals.length > 0 ? (
                                    referrals.map((referral, index) => (
                                        <ReferralHistoryRow
                                            key={referral.id}
                                            referral={referral}
                                        />
                                    ))
                                ) : (
                                    <tr>
                                        <td colSpan="5" className="ecre-px-5 ecre-py-8 ecre-text-center ecre-text-gray-500">
                                            {translate('referral_history_no_history')}
                                        </td>
                                    </tr>
                                )}
                            </tbody>
                        </table>
                    </div>

                    {paginationInfo.total_pages > 1 && (
                        <Pagination
                            currentPage={paginationInfo.current_page}
                            totalPages={paginationInfo.total_pages}
                            onPageChange={handlePageChange}
                        />
                    )}
                </>
            )}


            {/* ADD - Customize Referral Options Modal */}
            <Modal className='echorewards-reward-management' openModal={isOpenReferralOptions} toggleModal={handleReferralOptionsToggleModal}>
                {{
                    header: <div className="title ecre-text-gray-900 ecre-text-base ecre-font-semibold">{translate('referral_history_customize_options')}</div>,
                    body: (
                        <>
                            {/* Referral Coupon Type - FIXED to match ReferralTab.jsx pattern */}
                            <div className="referral-type__field ecre-mb-8">
                                <label htmlFor="referral_coupon_type" className="ecre-text-gray-500 ecre-text-sm ecre-font-medium ecre-inline-block ecre-pb-2">
                                    <span className="ecre-mr-2.5">{translate('referral_history_referral_coupon_type')}</span>
                                    <Tooltip className="align-[-2px] ecre-mr-1" content={hasCustomSettings ? translate('referral_history_coupon_type_tooltip') : translate('referral_history_coupon_type_global_tooltip')} />
                                </label>
                                <div className="input-wrapper__inner">
                                    <div className="input-wrap ecre-w-full ecre-inline-block" style={{ maxWidth: '320px' }}>
                                        <input
                                            id="referral_coupon_type"
                                            type="text"
                                            value={(() => {
                                                // Show custom settings if they exist, otherwise show global
                                                let value;
                                                if (hasCustomSettings && userCustomSettings?.referralCouponType) {
                                                    value = userCustomSettings.referralCouponType.value || userCustomSettings.referralCouponType;
                                                } else {
                                                    value = customReferralCouponType ? customReferralCouponType.value : formData.referralCouponType?.value;
                                                }

                                                const labelMap = {
                                                    'percent': translate('referral_history_percent_label'),
                                                    'fixed': translate('referral_history_fixed_label'),
                                                    'sign_up_fee': translate('referral_history_sign_up_fee_discount'),
                                                    'sign_up_fee_percent': translate('referral_history_sign_up_fee_percent'),
                                                    'recurring_fee': translate('referral_history_recurring_discount'),
                                                    'recurring_percent': translate('referral_history_recurring_percent')
                                                };
                                                return labelMap[value] || value;
                                            })()}
                                            disabled={true}
                                            readOnly
                                            className="!ecre-text-gray-500 !ecre-shadow-none !ecre-text-sm !ecre-font-normal !ecre-bg-gray-100 !ecre-p-[15px] ecre-w-full !ecre-rounded-lg !ecre-border !ecre-border-gray-300 ecre-cursor-not-allowed"
                                            style={{ maxWidth: '320px' }}
                                        />
                                    </div>
                                </div>
                            </div>

                            {/* Discount Amount */}
                            <div className="ecre-mb-8">
                                <Input
                                    id="referral_discount"
                                    label={(() => {
                                        // Get the effective coupon type from custom settings if available
                                        let effectiveType;
                                        if (hasCustomSettings && userCustomSettings?.referralCouponType) {
                                            effectiveType = userCustomSettings.referralCouponType.value || userCustomSettings.referralCouponType;
                                        } else {
                                            effectiveType = getEffectiveReferralCouponType();
                                        }

                                        return `${translate('discount_capital')} ${effectiveType === 'sign_up_fee'
                                            ? translate('sign_up_fee')
                                            : effectiveType === 'sign_up_fee_percent'
                                                ? translate('sign_up_fee')
                                                : effectiveType === 'recurring_fee'
                                                    ? translate('recurring_fee')
                                                    : effectiveType === 'recurring_percent'
                                                        ? translate('recurring_fee')
                                                        : translate(effectiveType)
                                            } ${translate('amount_lower')} ${['sign_up_fee_percent', 'recurring_percent', 'percent'].includes(effectiveType)
                                                ? '(%)'
                                                : `(${currency})`
                                            }`;
                                    })()}
                                    tooltip={translate('discount_percent_tooltip')}
                                    type="number"
                                    value={customReferralDiscount}
                                    onChange={(e) => setCustomReferralDiscount(e.target.value)}
                                    width='100%'
                                    min="0"
                                    max="100"
                                />
                            </div>

                            {/* Discount Capping */}
                            <div className="ecre-mb-8">
                                <Input
                                    id="referral_discount_capping"
                                    label={`${translate('discount_capping_label')} (${currency})`}
                                    tooltip={translate('discount_capping_tooltip')}
                                    type="number"
                                    value={referralDiscountCapping}
                                    onChange={(e) => setReferralDiscountCapping(e.target.value)}
                                    width='100%'
                                    min="0"
                                />
                            </div>

                            {/* Monthly Referral Limit */}
                            <div className="ecre-mb-8">
                                <Switcher
                                    id="enable_referral_limit"
                                    checked={enableReferralLimit}
                                    onChange={(e) => setEnableReferralLimit(e.target.checked)}  // FIXED - proper event handling
                                    label={translate('enable_referral_limit_label')}
                                    tooltip={translate('enable_referral_limit_tooltip')}
                                />
                                {enableReferralLimit && (
                                    <Input
                                        id="referral_monthly_limit"
                                        label={translate('monthly_referral_limit_label')}
                                        tooltip={translate('monthly_referral_limit_tooltip')}
                                        type="number"
                                        value={referralMonthlyLimit}
                                        onChange={(e) => setReferralMonthlyLimit(e.target.value)}
                                        marginTop='ecre-mt-2'
                                        width='100%'
                                        min="1"
                                        placeholder={translate('referral_history_enter_monthly_limit')}
                                    />
                                )}
                            </div>

                            {/* Minimum Purchase Amount */}
                            <div className="ecre-mb-8">
                                <Input
                                    id="referral_minimum_purchase"
                                    label={`${translate('min_purchase_amount_label')} (${currency})`}
                                    tooltip={translate('min_purchase_amount_tooltip')}
                                    type="number"
                                    value={referralMinimumPurchase}
                                    onChange={(e) => setReferralMinimumPurchase(e.target.value)}
                                    width='100%'
                                    min="0"
                                />
                            </div>
                        </>
                    ),
                    footer: (
                        <div className="btn-box ecre-flex ecre-justify-between ecre-flex-wrap ecre-items-center ecre-gap-4">
                            <button
                                onClick={() => setIsOpenResetModal(true)}
                                disabled={!hasCustomSettings}
                                className="ecre-cursor-pointer ecre-text-sm ecre-font-semibold ecre-px-4 ecre-py-2.5 ecre-transition ecre-border ecre-border-solid ecre-border-red-500 ecre-rounded-lg ecre-bg-white ecre-text-red-500 hover:ecre-bg-red-500 hover:ecre-text-white disabled:ecre-opacity-50 disabled:ecre-cursor-not-allowed"
                            >
                                {translate('referral_history_reset_to_default')}
                            </button>
                            <div className="btn-box ecre-flex ecre-flex-wrap ecre-items-center ecre-gap-2">
                                <button
                                    onClick={handleReferralOptionsToggleModal}
                                    disabled={settingsLoading}
                                    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 disabled:ecre-opacity-50"
                                >
                                    {translate('referral_history_cancel')}
                                </button>
                                <button
                                    onClick={handleSaveReferralSettings}
                                    disabled={settingsLoading}
                                    className="ecre-text-white ecre-cursor-pointer ecre-text-sm ecre-font-semibold ecre-px-4 ecre-py-2.5 ecre-bg-[#6A40D5] ecre-rounded-lg ecre-justify-center ecre-items-center ecre-gap-2 ecre-inline-flex ecre-transition-all ecre-border-none hover:ecre-bg-violet-700 disabled:ecre-opacity-50"
                                >
                                    {settingsLoading ? translate('referral_history_saving') : translate('referral_history_save_changes')}
                                </button>
                            </div>
                        </div>
                    )
                }}
            </Modal>

            {/* ADD - Reset Confirmation Modal */}
            <Modal openModal={isOpenResetModal} toggleModal={() => setIsOpenResetModal(false)}>
                {{
                    header: <div className="title ecre-text-gray-900 ecre-text-base ecre-font-semibold">{translate('referral_history_reset_title')}</div>,
                    body: (
                        <div className="description">
                            <div className="ecre-text-gray-900 ecre-text-sm ecre-font-normal ecre-mb-4">
                                {translate('referral_history_reset_description')}
                            </div>
                            <div className="ecre-text-gray-900 ecre-text-sm ecre-font-normal">
                                {translate('referral_history_reset_confirm')}
                            </div>
                        </div>
                    ),
                    footer: (
                        <div className="btn-box ecre-justify-end ecre-items-center ecre-gap-2 ecre-flex">
                            <button
                                onClick={() => setIsOpenResetModal(false)}
                                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('referral_history_cancel')}
                            </button>
                            <button
                                onClick={handleConfirmReset}
                                className="ecre-text-white ecre-cursor-pointer ecre-text-sm ecre-font-semibold ecre-px-4 ecre-py-2.5 ecre-transition ecre-border ecre-border-solid ecre-border-red-500 ecre-bg-red-500 ecre-rounded-lg hover:ecre-bg-white hover:ecre-text-red-500"
                            >
                                {translate('referral_history_reset_button')}
                            </button>
                        </div>
                    )
                }}
            </Modal>
        </div>
    );
}

export default ReferralHistory;