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

const RewardCoupons = () => {
    const {
        selectedReferrer,
        formData,
        handleSelectChange, // ADD this import
        rewardCouponTypeOptions,
        CouponTypeProOption,
        SubscriptionProOption,
        isPro,
        initialFormData, currency
    } = useContext(SettingsContext);

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

    // Add separate loading state for initial settings fetch
    const [settingsInitialLoading, setSettingsInitialLoading] = useState(true);



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

    // 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
    const [isOpenRewardCoupons, setIsOpenRewardCoupons] = useState(false);
    const [isOpenIssueRewardCoupon, setIsOpenIssueRewardCoupon] = useState(false);

    // ===== CUSTOMIZE MODAL STATES (for saving custom settings) =====
    // Add this state for the customize modal
    const [customRewardType, setCustomRewardType] = useState(null);
    const [customDiscountAmount, setCustomDiscountAmount] = useState('');
    const [discountCapping, setDiscountCapping] = useState('');
    const [enableExpiry, setEnableExpiry] = useState(false);
    const [couponValidity, setCouponValidity] = useState('');
    const [enableUsageLimit, setEnableUsageLimit] = useState(false);
    const [usageLimit, setUsageLimit] = useState('');
    const [minimumPurchase, setMinimumPurchase] = useState('');

    // ===== ISSUE MODAL STATES (for temporary reward creation) =====
    // Add this with your other issue modal states
    const [issueRewardType, setIssueRewardType] = useState(null);
    const [issueDiscountAmount, setIssueDiscountAmount] = useState('');
    const [issueDiscountCapping, setIssueDiscountCapping] = useState('');
    const [issueEnableExpiry, setIssueEnableExpiry] = useState(false);
    const [issueValidityDays, setIssueValidityDays] = useState('');
    const [issueEnableUsageLimit, setIssueEnableUsageLimit] = useState(false);
    const [issueUsageLimit, setIssueUsageLimit] = useState('');
    const [issueMinimumPurchase, setIssueMinimumPurchase] = useState('');
    // Add this with your other state declarations
    const [isOpenResetModal, setIsOpenResetModal] = useState(false);

    // ADD - Create filtered options without 'reward_point' for both modals
    const rewardCouponTypeOptionsWithoutPoints = useMemo(() => {
        return rewardCouponTypeOptions?.filter(option => option.value !== 'reward_point') || [];
    }, [rewardCouponTypeOptions]);



    // Fetch reward coupons data
    const fetchRewardCoupons = 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_reward_coupons');
            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) {
                setRewardCoupons(response.data.data.reward_coupons);
                setPaginationInfo(response.data.data.pagination);
            } else {
                console.error('Failed to fetch reward coupons:', response.data.data);
            }
        } catch (error) {
            console.error('Error fetching reward coupons:', error);
        } finally {
            setLoading(false);
            setIsPaginating(false);
        }
    };

    // UPDATE - Fix loadCouponSettings to use proper global defaults
    const loadCouponSettings = async () => {
        if (!selectedReferrer || !selectedReferrer.user_id) {
            setSettingsInitialLoading(false);
            return;
        }

        setSettingsInitialLoading(true);
        const result = await fetchUserCustomSettings(selectedReferrer.user_id);
        if (result) {
            const rewardTypeValue = result.getEffectiveValue('rewardType', formData.rewardType)?.value;
            const rewardTypeOption = rewardCouponTypeOptions.find(opt => opt.value === rewardTypeValue);

            setCustomRewardType(rewardTypeOption || formData.rewardType);

            // Load other settings
            setCustomDiscountAmount(result.getEffectiveValue('rewardDiscount', formData.rewardDiscount || ''));
            setDiscountCapping(result.getEffectiveValue('rewardDiscountCapping', formData.rewardDiscountCapping || ''));
            setEnableExpiry(result.getEffectiveValue('enableRewardExpiry', formData.enableRewardExpiry || false));
            setCouponValidity(result.getEffectiveValue('rewardCouponValidity', formData.rewardCouponValidity || ''));
            setEnableUsageLimit(result.getEffectiveValue('enableRewardCouponUsageLimit', formData.enableRewardCouponUsageLimit || false));
            setUsageLimit(result.getEffectiveValue('rewardCouponUsageLimit', formData.rewardCouponUsageLimit || ''));
            setMinimumPurchase(result.getEffectiveValue('rewardMinimumPurchaseAmount', formData.rewardMinimumPurchaseAmount || ''));
            setIssueRewardType(rewardTypeOption.value);
        } else {
            // Set global defaults
            setCustomRewardType(formData.rewardType);
            setCustomDiscountAmount(formData.rewardDiscount || '');
            setDiscountCapping(formData.rewardDiscountCapping || '');
            setEnableExpiry(formData.enableRewardExpiry || false);
            setCouponValidity(formData.rewardCouponValidity || '');
            setEnableUsageLimit(formData.enableRewardCouponUsageLimit || false);
            setUsageLimit(formData.rewardCouponUsageLimit || '');
            setMinimumPurchase(formData.rewardMinimumPurchaseAmount || '');
            setIssueRewardType(formData.rewardType?.value || '');
        }
        setSettingsInitialLoading(false);
    };

    // ADD - Save coupon settings
    const handleSaveCouponSettings = async () => {
        if (!selectedReferrer || !selectedReferrer.user_id) return;

        const settings = {
            rewardType: customRewardType ? customRewardType : formData.rewardType,
            rewardDiscount: customDiscountAmount || formData.rewardDiscount || 0,
            rewardDiscountCapping: discountCapping || 0,
            enableRewardExpiry: enableExpiry ? 1 : 0,
            enableRewardCouponUsageLimit: enableUsageLimit ? 1 : 0,
            rewardMinimumPurchaseAmount: minimumPurchase || 0
        };

        // Only include conditional settings if enabled and have values
        if (enableExpiry && couponValidity > 0) {
            settings.rewardCouponValidity = couponValidity;
        }

        if (enableUsageLimit && usageLimit > 0) {
            settings.rewardCouponUsageLimit = usageLimit;
        }

        const result = await saveUserCustomSettings(selectedReferrer.user_id, settings);
        if (result.success) {
            setIsOpenRewardCoupons(false);
            // Update issue reward type with the value, not the whole object
            setIssueRewardType(settings.rewardType?.value || settings.rewardType);
        } else {
            console.error('Failed to save coupon settings:', result.error);
        }
    };

    // UPDATE - Reset with proper formData defaults
    const handleResetCouponSettings = async () => {
        if (!selectedReferrer || !selectedReferrer.user_id) return;

        const result = await resetToDefaultSettings(selectedReferrer.user_id);
        if (result.success) {
            // Reset all fields to global defaults
            setCustomRewardType(formData.rewardType);
            setCustomDiscountAmount(formData.rewardDiscount || '');
            setDiscountCapping(formData.rewardDiscountCapping || '');
            setEnableExpiry(formData.enableRewardExpiry || false);
            setCouponValidity(formData.rewardCouponValidity || '');
            setEnableUsageLimit(formData.enableRewardCouponUsageLimit || false);
            setUsageLimit(formData.rewardCouponUsageLimit || '');
            setMinimumPurchase(formData.rewardMinimumPurchaseAmount || '');
        } else {
            console.error('Failed to reset coupon settings:', result.error);
        }
    };

    // Fix the reset handler - use the hook's resetToDefaultSettings function
    const handleConfirmReset = async () => {
        try {
            if (!selectedReferrer?.user_id) return;

            // Use the hook's reset function
            await resetToDefaultSettings(selectedReferrer.user_id);

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

            // Refresh the data to reflect changes
            await fetchRewardCoupons();
            await loadCouponSettings(); // Reload settings to update hasCustomSettings

        } catch (error) {
            console.error('Error resetting settings:', error);
        }
    };

    // ADD - Issue reward coupon
    const handleIssueRewardCoupon = async () => {
        if (!selectedReferrer || !selectedReferrer.user_id) return;

        try {
            const issueData = new FormData();
            issueData.append('action', 'ecre_issue_reward_coupon');
            issueData.append('nonce', ecreAdmin.nonce);
            issueData.append('user_id', selectedReferrer.user_id);
            issueData.append('discount_amount', issueDiscountAmount || formData.rewardDiscount || 0);
            issueData.append('discount_capping', issueDiscountCapping || 0);
            issueData.append('enable_expiry', issueEnableExpiry ? 1 : 0);
            issueData.append('validity_days', issueEnableExpiry ? (issueValidityDays || 0) : 0);
            issueData.append('enable_usage_limit', issueEnableUsageLimit ? 1 : 0);
            issueData.append('usage_limit', issueEnableUsageLimit ? (issueUsageLimit || 1) : '');
            issueData.append('minimum_purchase', issueMinimumPurchase || 0);
            issueData.append('reward_type', issueRewardType || 'percent');

            const response = await axios.post(ecreAdmin.ajaxurl, issueData);

            if (response.data.success) {
                fetchRewardCoupons();
                setIsOpenIssueRewardCoupon(false); // This will trigger the reset in toggle function
            } else {
                console.error('Failed to issue reward coupon:', response.data.data);
            }
        } catch (error) {
            console.error('Error issuing reward coupon:', error);
        }
    };

    // ADD - Modal handlers
    const handleRewardCouponsToggleModal = () => {
        if (!isOpenRewardCoupons) {
            // Don't show loading when opening edit modal - settings are already loaded
            // loadCouponSettings(); // Remove this call since settings are already loaded
        }
        setIsOpenRewardCoupons(!isOpenRewardCoupons);
    };

    // UPDATE - Initialize issue form with proper formData defaults
    const handleIssueRewardCouponToggleModal = async () => {
        if (!isOpenIssueRewardCoupon) {
            // Load current effective settings (merged custom + global)
            const result = await fetchUserCustomSettings(selectedReferrer.user_id);

            if (result) {
                // Use merged/effective values (custom + global defaults)
                const effectiveRewardType = result.getEffectiveValue('rewardType', formData.rewardType);
                setIssueRewardType(effectiveRewardType?.value || effectiveRewardType);

                setIssueDiscountAmount(result.getEffectiveValue('rewardDiscount', formData.rewardDiscount || ''));
                setIssueDiscountCapping(result.getEffectiveValue('rewardDiscountCapping', formData.rewardDiscountCapping || ''));
                setIssueEnableExpiry(result.getEffectiveValue('enableRewardExpiry', formData.enableRewardExpiry || false));
                setIssueValidityDays(result.getEffectiveValue('rewardCouponValidity', formData.rewardCouponValidity || ''));
                setIssueEnableUsageLimit(result.getEffectiveValue('enableRewardCouponUsageLimit', formData.enableRewardCouponUsageLimit || false));
                setIssueUsageLimit(result.getEffectiveValue('rewardCouponUsageLimit', formData.rewardCouponUsageLimit || ''));
                setIssueMinimumPurchase(result.getEffectiveValue('rewardMinimumPurchaseAmount', formData.rewardMinimumPurchaseAmount || ''));
            } else {
                // Use global defaults only
                setIssueRewardType(formData.rewardType?.value || formData.rewardType);
                setIssueDiscountAmount(formData.rewardDiscount || '');
                setIssueDiscountCapping(formData.rewardDiscountCapping || '');
                setIssueEnableExpiry(formData.enableRewardExpiry || false);
                setIssueValidityDays(formData.rewardCouponValidity || '');
                setIssueEnableUsageLimit(formData.enableRewardCouponUsageLimit || false);
                setIssueUsageLimit(formData.rewardCouponUsageLimit || '');
                setIssueMinimumPurchase(formData.rewardMinimumPurchaseAmount || '');
            }
        } else {
            // Modal is closing - reset to effective values again
            const result = await fetchUserCustomSettings(selectedReferrer.user_id);

            if (result) {
                setIssueDiscountAmount(result.getEffectiveValue('rewardDiscount', formData.rewardDiscount || ''));
                setIssueDiscountCapping(result.getEffectiveValue('rewardDiscountCapping', formData.rewardDiscountCapping || ''));
                setIssueEnableExpiry(result.getEffectiveValue('enableRewardExpiry', formData.enableRewardExpiry || false));
                setIssueValidityDays(result.getEffectiveValue('rewardCouponValidity', formData.rewardCouponValidity || ''));
                setIssueEnableUsageLimit(result.getEffectiveValue('enableRewardCouponUsageLimit', formData.enableRewardCouponUsageLimit || false));
                setIssueUsageLimit(result.getEffectiveValue('rewardCouponUsageLimit', formData.rewardCouponUsageLimit || ''));
                setIssueMinimumPurchase(result.getEffectiveValue('rewardMinimumPurchaseAmount', formData.rewardMinimumPurchaseAmount || ''));
                setIssueRewardType(formData.rewardType.value);
            } else {
                setIssueDiscountAmount(formData.rewardDiscount || '');
                setIssueDiscountCapping(formData.rewardDiscountCapping || '');
                setIssueEnableExpiry(formData.enableRewardExpiry || false);
                setIssueValidityDays(formData.rewardCouponValidity || '');
                setIssueEnableUsageLimit(formData.enableRewardCouponUsageLimit || false);
                setIssueUsageLimit(formData.rewardCouponUsageLimit || '');
                setIssueMinimumPurchase(formData.rewardMinimumPurchaseAmount || '');
                setIssueRewardType(formData.rewardType.value || '');
            }
        }

        setIsOpenIssueRewardCoupon(!isOpenIssueRewardCoupon);
    };

    // REPLACE your existing getRewardCouponText function with this UPDATED version
    const getRewardCouponText = () => {
        // Show loading message while settings are initially loading
        if (settingsInitialLoading) {
            return translate('loading_settings') || 'Loading...';
        }

        // Use SAVED settings instead of current form state
        const savedRewardType = hasCustomSettings
            ? userCustomSettings?.rewardType           // Saved custom reward type (now an array)
            : formData.rewardType;                     // Global reward type

        const savedRewardDiscount = hasCustomSettings
            ? (userCustomSettings?.rewardDiscount || formData.rewardDiscount || 0)       // Saved custom discount with fallback
            : (formData.rewardDiscount || 0);                 // Global discount with fallback

        const savedRewardPoint = hasCustomSettings
            ? userCustomSettings?.rewardPoint          // Saved custom reward point
            : formData.rewardPoint;                    // Global reward point

        // Extract the actual value from the reward type object/array
        const effectiveRewardType = (() => {
            let rewardTypeValue;

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

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

        // Check if reward type is reward_point
        if (effectiveRewardType === 'reward_point') {
            // If user has custom settings and the custom reward type is reward_point
            if (hasCustomSettings) {
                return translate('custom_points_settings_warning_message');
            } else {
                // If it's a global setting issue
                return translate('reward_coupons_reward_points_warning');
            }
        }


        // Ensure we have a valid discount value
        const discountValue = savedRewardDiscount || 0;

        let rewardText = '';

        switch (effectiveRewardType) {
            case 'percent':
                rewardText = `${translate('reward_coupons_gets_percent_coupon')} ${discountValue}% ${translate('reward_coupons_coupon_for_referral')}`;
                break;
            case 'fixed':
                rewardText = `${translate('reward_coupons_gets_percent_coupon')} ${currency}${discountValue} ${translate('reward_coupons_coupon_for_referral')}`;
                break;
            case 'sign_up_fee':
                rewardText = `${translate('reward_coupons_gets_percent_coupon')} ${currency}${discountValue} ${translate('reward_coupons_sign_up_fee_discount')}`;
                break;
            case 'sign_up_fee_percent':
                rewardText = `${translate('reward_coupons_gets_percent_coupon')} ${discountValue}% ${translate('reward_coupons_sign_up_fee_discount')}`;
                break;
            case 'recurring_fee':
                rewardText = `${translate('reward_coupons_gets_percent_coupon')} ${currency}${discountValue} ${translate('reward_coupons_recurring_fee_discount')}`;
                break;
            case 'recurring_percent':
                rewardText = `${translate('reward_coupons_gets_percent_coupon')} ${discountValue}% ${translate('reward_coupons_recurring_fee_discount')}`;
                break;
            default:
                rewardText = `${translate('reward_coupons_gets_percent_coupon')} ${discountValue}% ${translate('reward_coupons_coupon_for_referral')}`;
        }

        // Add custom settings indicator if applicable
        if (hasCustomSettings) {
            return `${rewardText}`;
        }

        return rewardText;
    };

    // Also add this helper function to check if reward type is reward_point (for hiding the Edit button)
    const isRewardPointType = () => {
        // Don't hide the edit button while loading
        if (settingsInitialLoading) {
            return false;
        }

        const savedRewardType = hasCustomSettings
            ? userCustomSettings?.rewardType
            : formData.rewardType;

        let rewardTypeValue;

        if (hasCustomSettings && savedRewardType) {
            rewardTypeValue = savedRewardType.value || savedRewardType;
        } else {
            rewardTypeValue = formData.rewardType?.value || formData.rewardType;
        }

        const effectiveRewardType = isPro
            ? rewardTypeValue
            : (['sign_up_fee', 'sign_up_fee_percent', 'recurring_fee', 'reward_point', 'recurring_percent'].includes(rewardTypeValue)
                ? initialFormData.rewardType?.value
                : rewardTypeValue);

        return effectiveRewardType === 'reward_point';
    };

    // This should be placed after your useState declarations and before getRewardCouponText()
    // Update this function to use custom reward type when available
    const getEffectiveRewardType = () => {
        const currentRewardType = customRewardType || formData.rewardType;
        return isPro
            ? currentRewardType.value
            : (['sign_up_fee', 'sign_up_fee_percent', 'recurring_fee', 'reward_point', 'recurring_percent'].includes(currentRewardType.value)
                ? initialFormData.rewardType.value
                : currentRewardType.value);
    };

    // UPDATE existing useEffect to include custom settings loading
    useEffect(() => {
        fetchRewardCoupons();
        loadCouponSettings(); // ADD this line
    }, [selectedReferrer, currentPage, itemsPerPage, timeFilter]);

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

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

    // Clear active filters
    const clearFilters = () => {
        setTimeFilter('All Time');
        setCurrentPage(1);
    };

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

    // Calculate display indices for SelectPerPagination
    const startIndex = (paginationInfo.current_page - 1) * paginationInfo.per_page + 1;
    const endIndex = Math.min(startIndex + rewardCoupons.length - 1, paginationInfo.total_items);


    return (
        <div className="referrer-details__reward-coupons">
            {!isPro ? (
                <div className="ecre-px-8 ecre-py-16 ecre-bg-white ecre-rounded-lg ecre-flex ecre-text-center ecre-flex-col ecre-justify-start ecre-items-center ecre-gap-4">
                    <div className="ecre-text-gray-900 ecre-text-sm ecre-font-medium">🎉 {translate('reward_coupons_customize_rewards')}</div>
                    <div className="ecre-max-w-[420px] ecre-text-gray-600 ecre-text-sm ecre-font-normal mx-auto">{translate('reward_coupons_upgrade_description')}</div>
                    <button className='ecre-px-4 ecre-cursor-pointer ecre-border-0 ecre-inline-flex ecre-items-center ecre-pt-[10px] ecre-pb-[10px] ecre-bg-fuchsia-100 ecre-rounded-[500px] ecre-text-fuchsia-950 ecre-text-sm ecre-font-semibold ecre-transition hover:ecre-bg-[#f0cdfa]' 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 ecre-ml-2">{translate('reward_coupons_unlock_custom_rewards')}</span>
                    </button>
                </div>
            ) : (
                <>
                    <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 items-center ecre-gap-5">
                        <div className="ecre-text-sm ecre-text-gray-600 ecre-font-medium">{translate('reward_coupons_reward')}
                            <span className="ecre-text-gray-900 ecre-font-normal ecre-ml-2"> {getRewardCouponText()}</span>

                            {hasCustomSettings && (
                                <CustomizedPill />
                            )}
                        </div>

                        {!isRewardPointType() && (
                            <div onClick={handleRewardCouponsToggleModal} className="ecre-text-[#3b71ca] ecre-text-sm ecre-font-medium ecre-cursor-pointer ecre-transition hover:ecre-text-[#6a40d5]">
                                {translate('reward_coupons_edit')}
                            </div>
                        )}
                    </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={startIndex}
                                endIndex={endIndex}
                                totalItems={paginationInfo.total_items}
                                itemsPerPage={itemsPerPage}
                                onItemsPerPageChange={handleItemsPerPageChange}
                            />

                            <button onClick={handleIssueRewardCouponToggleModal} className="ecre-ml-auto ecre-cursor-pointer ecre-flex ecre-items-center ecre-gap-2 ecre-px-3 ecre-pt-[7px] ecre-pb-[6px] ecre-bg-white ecre-text-[#6a40d5] ecre-text-sm ecre-font-semibold ecre-rounded-lg ecre-border ecre-border-[#6a40d5] !ecre-shadow-none">
                                <span className="icon ecre-leading-[1]">{ecreIcons.circlePlus}</span> {translate('reward_coupons_issue_new_reward')}
                            </button>

                            <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('reward_coupons_clear_filter')}
                                    <span className="icon ecre-ml-1">{ecreIcons.circleClose}</span>
                                </div>
                            </div>
                        )}
                    </div>

                    {loading ? (
                        <div className="ecre-text-center ecre-py-8">{translate('reward_coupons_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('reward_coupons_reward_coupon')}
                                            </th>
                                            <th className="ecre-px-5 ecre-py-4 ecre-text-left ecre-text-sm ecre-font-normal ecre-text-gray-600">
                                                {translate('reward_coupons_amount')}
                                            </th>
                                            <th className="ecre-px-5 ecre-py-4 ecre-text-left ecre-text-sm ecre-font-normal ecre-text-gray-600">
                                                {translate('reward_coupons_usage_limit')}
                                            </th>
                                            <th className="ecre-px-5 ecre-py-4 ecre-text-left ecre-text-sm ecre-font-normal ecre-text-gray-600">
                                                {translate('reward_coupons_type')}
                                            </th>
                                            <th className="ecre-px-5 ecre-py-4 ecre-text-left ecre-text-sm ecre-font-normal ecre-text-gray-600">
                                                {translate('reward_coupons_status')}
                                            </th>
                                            <th className="ecre-px-5 ecre-py-4 ecre-text-left ecre-text-sm ecre-font-normal ecre-text-gray-600">
                                                {translate('reward_coupons_actions')}
                                            </th>
                                        </tr>
                                    </thead>
                                    <tbody className="ecre-bg-white ecre-divide-y ecre-divide-gray-200">
                                        {rewardCoupons && rewardCoupons.length > 0 ? (
                                            rewardCoupons.map((coupon, index) => (
                                                <RewardCouponsRow
                                                    key={coupon.id}
                                                    coupon={coupon}
                                                />
                                            ))
                                        ) : (
                                            <tr>
                                                <td colSpan="6" className="ecre-px-5 ecre-py-8 ecre-text-center ecre-text-gray-500">
                                                    {translate('reward_coupons_no_coupons_found')}
                                                </td>
                                            </tr>
                                        )}
                                    </tbody>
                                </table>
                            </div>

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

                </>
            )}



            {/* ADD - Customize Reward Coupon Options Modal */}
            <Modal className='echorewards-reward-management' openModal={isOpenRewardCoupons} toggleModal={handleRewardCouponsToggleModal}>
                {{
                    header: <div className="title ecre-text-gray-900 ecre-text-base ecre-font-semibold">{translate('reward_coupons_customize_options')}</div>,
                    // REPLACE the reward type section with full implementation
                    body: (
                        <>
                            {/* FIX - Complete reward type implementation like RewardTab */}
                            <div className="reward-type__field ecre-mb-8">
                                {/* In Customize Reward Coupon Options Modal */}
                                <EcreSelectPro
                                    id="reward_type"
                                    label={translate('reward_coupons_reward_type')}
                                    options={rewardCouponTypeOptionsWithoutPoints}
                                    value={customRewardType ? customRewardType.value : formData.rewardType.value}
                                    onChange={(selectedOption) => setCustomRewardType(selectedOption)} // Use custom state
                                    width="320"
                                    classNamePrefix="echorewards-select"
                                    isSearchable={false}
                                    placeholder={translate('select_reward_type')}
                                    tooltip="Type of reward to be given to referrers"
                                    components={{ Option: !isPro ? CouponTypeProOption : SubscriptionProOption }}
                                    isPro={isPro}
                                    isDisabled={false}
                                    isOptionDisabled={(option) => {
                                        let disabledOptions = ['sign_up_fee', 'sign_up_fee_percent', 'reward_point', 'recurring_fee', 'recurring_percent'];
                                        if (isPro && !ecreAdmin.is_woocommerce_subscriptions_active) {
                                            disabledOptions = disabledOptions.filter((opt) => opt !== 'reward_point');
                                        }
                                        return disabledOptions.includes(option.value);
                                    }}
                                />
                            </div>

                            {/* Show different fields based on effective reward type */}
                            {getEffectiveRewardType() !== 'reward_point' && (
                                <>
                                    <div className="form-group ecre-mb-4">
                                        <Input
                                            id="discount_amount"
                                            label={`${translate('discount_capital')} ${getEffectiveRewardType() === 'sign_up_fee'
                                                ? translate('sign_up_fee')
                                                : getEffectiveRewardType() === 'sign_up_fee_percent'
                                                    ? translate('sign_up_fee')
                                                    : getEffectiveRewardType() === 'recurring_fee'
                                                        ? translate('recurring_fee')
                                                        : getEffectiveRewardType() === 'recurring_percent'
                                                            ? translate('recurring_fee')
                                                            : getEffectiveRewardType()
                                                } ${translate('amount_lower')} ${['sign_up_fee_percent', 'recurring_percent', 'percent'].includes(getEffectiveRewardType())
                                                    ? '(%)'
                                                    : `(${currency})`
                                                }`}
                                            tooltip={translate('discount_tooltip')}
                                            type="number"
                                            value={customDiscountAmount || ''}
                                            onChange={(e) => setCustomDiscountAmount(e.target.value)}
                                            width='100%'
                                            placeholder={`${translate('default_val')}: ${formData.rewardDiscount || 0}`}
                                        />

                                    </div>

                                    {/* Discount capping for percentage types */}
                                    {getEffectiveRewardType() === 'percent' && (
                                        <div className="form-group ecre-mb-4">
                                            <Input
                                                id="discount_capping"
                                                label={`${translate('discount_capping')} (${currency})`}
                                                tooltip={translate('discount_capping_tooltip')}
                                                type="number"
                                                value={discountCapping || ''}
                                                onChange={(e) => setDiscountCapping(e.target.value)}
                                                width='100%'
                                                min="0"
                                                placeholder={`${translate('default_val')}: ${formData.rewardDiscountCapping || translate('no_limit')}`}
                                            />
                                        </div>
                                    )}

                                    {/* Enable expiry date switcher */}
                                    <div className="form-group ecre-mb-4">
                                        <Switcher
                                            id="enable_expiry_date"
                                            checked={enableExpiry}
                                            onChange={(e) => setEnableExpiry(e.target.checked)}
                                            label={translate('enable_reward_expiry')}
                                            tooltip={translate('enable_reward_expiry_tooltip')}
                                            marginTop='ecre-mt-2'
                                        />
                                    </div>

                                    {/* Coupon validity days */}
                                    {enableExpiry && (
                                        <div className="form-group ecre-mb-4">
                                            <Input
                                                id="reward_coupon_validity"
                                                label={translate('reward_coupon_validity')}
                                                tooltip={translate('reward_coupon_validity_tooltip')}
                                                type="number"
                                                value={couponValidity || ''}
                                                onChange={(e) => setCouponValidity(e.target.value)}
                                                marginTop='ecre-mt-2'
                                                width='100%'
                                                min="1"
                                                placeholder={`${translate('default_val')}: ${formData.rewardCouponValidity || translate('no_expiry')} ${translate('days_lower')}`}
                                            />
                                        </div>
                                    )}

                                    {/* Limit coupon usage switcher */}
                                    <div className="form-group ecre-mb-4">
                                        <Switcher
                                            id="limit_reward_coupon_usage"
                                            checked={enableUsageLimit}
                                            onChange={(e) => setEnableUsageLimit(e.target.checked)}
                                            label={translate('reward_coupon_usage_limit')}
                                            tooltip={translate('reward_coupon_usage_limit_tooltip')}
                                            marginTop='ecre-mt-2'
                                        />
                                    </div>

                                    {/* Usage limit */}
                                    {enableUsageLimit && (
                                        <div className="form-group ecre-mb-4">
                                            <Input
                                                id="coupon_usage_limit"
                                                label={translate('how_many_times_coupon_used')}
                                                tooltip={translate('reward_coupon_usages_limit')}
                                                type="number"
                                                value={usageLimit || ''}
                                                onChange={(e) => setUsageLimit(e.target.value)}
                                                marginTop='ecre-mt-2'
                                                width='100%'
                                                min="1"
                                                placeholder={`${translate('default_val')}: ${formData.rewardCouponUsageLimit || 1}`}
                                            />
                                        </div>
                                    )}

                                    {/* Minimum purchase amount */}
                                    <div className="form-group ecre-mb-8">
                                        <Input
                                            id="minimum_purchase_amount"
                                            label={`${translate('min_purchase_reward_coupon')} (${currency})`}
                                            tooltip={translate('min_purchase_reward_tooltip')}
                                            type="number"
                                            value={minimumPurchase || ''}
                                            onChange={(e) => setMinimumPurchase(e.target.value)}
                                            width='100%'
                                            min="0"
                                            placeholder={`${translate('default_val')}: ${formData.rewardMinimumPurchaseAmount || 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('reward_coupons_reset_to_default')}
                            </button>
                            <div className="btn-box ecre-flex ecre-flex-wrap ecre-items-center ecre-gap-2">
                                <button
                                    onClick={handleRewardCouponsToggleModal}
                                    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('reward_coupons_cancel')}
                                </button>
                                <button
                                    onClick={handleSaveCouponSettings}
                                    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('reward_coupons_saving') : translate('reward_coupons_save_changes')}
                                </button>
                            </div>
                        </div>
                    )
                }}
            </Modal>


            {/* Issue New Reward Modal - Fixed version */}
            <Modal className='echorewards-reward-management' openModal={isOpenIssueRewardCoupon} toggleModal={handleIssueRewardCouponToggleModal}>
                {{
                    header: <div className="title ecre-text-gray-900 ecre-text-base ecre-font-semibold">{translate('reward_coupons_issue_new_reward_title')}</div>,
                    body: (
                        <>
                            <div className="reward-type__field ecre-mb-8">
                                <EcreSelectPro
                                    id="reward_type"
                                    label={translate('reward_type')}
                                    options={rewardCouponTypeOptionsWithoutPoints}
                                    value={issueRewardType ? (issueRewardType === 'reward_point' ? 'percent' : issueRewardType) : (formData.rewardType.value === 'reward_point' ? 'percent' : formData.rewardType.value)}
                                    onChange={(selectedOption) => setIssueRewardType(selectedOption.value)} // Use custom state
                                    width="320"
                                    classNamePrefix="echorewards-select"
                                    isSearchable={false}
                                    placeholder={translate('select_reward_type_placeholder')}
                                    tooltip={translate('reward_type_tooltip')}
                                    components={{ Option: !isPro ? CouponTypeProOption : SubscriptionProOption }}
                                    isPro={isPro}
                                    isDisabled={false}
                                    isOptionDisabled={(option) => {
                                        let disabledOptions = ['sign_up_fee', 'sign_up_fee_percent', 'reward_point', 'recurring_fee', 'recurring_percent'];
                                        if (isPro && !ecreAdmin.is_woocommerce_subscriptions_active) {
                                            disabledOptions = disabledOptions.filter((opt) => opt !== 'reward_point');
                                        }
                                        return disabledOptions.includes(option.value);
                                    }}
                                />
                            </div>

                            {/* Discount amount field  */}
                            <div className="form-group ecre-mb-4">
                                <Input
                                    id="issue_discount_amount"
                                    label={`${translate('discount_capital')} ${issueRewardType === 'sign_up_fee'
                                        ? translate('sign_up_fee')
                                        : issueRewardType === 'sign_up_fee_percent'
                                            ? translate('sign_up_fee')
                                            : issueRewardType === 'recurring_fee'
                                                ? translate('recurring_fee')
                                                : issueRewardType === 'recurring_percent'
                                                    ? translate('recurring_fee')
                                                    : issueRewardType === 'reward_point'
                                                        ? translate('percent')
                                                        : translate(issueRewardType)
                                        } ${translate('amount_lower')} ${['sign_up_fee_percent', 'recurring_percent', 'percent', 'reward_point'].includes(issueRewardType)
                                            ? '(%)'
                                            : `(${currency})`
                                        }`}
                                    tooltip={translate('discount_tooltip')}
                                    type="number"
                                    value={issueDiscountAmount || ''}
                                    onChange={(e) => setIssueDiscountAmount(e.target.value)}
                                    width='100%'
                                />
                            </div>

                            {/* Discount capping for percentage types */}
                            {(issueRewardType === 'percent' || issueRewardType === 'reward_point') && (
                                <div className="form-group ecre-mb-4">
                                    <Input
                                        id="issue_discount_capping"
                                        label={`${translate('discount_capping')} (${currency})`}
                                        tooltip={translate('discount_capping_tooltip')}
                                        type="number"
                                        value={issueDiscountCapping || ''}
                                        onChange={(e) => setIssueDiscountCapping(e.target.value)}
                                        width='100%'
                                        min="0"
                                    />
                                </div>
                            )}

                            {/* Enable expiry date switcher */}
                            <div className="form-group ecre-mb-4">
                                <Switcher
                                    id="issue_enable_expiry_date"
                                    checked={issueEnableExpiry}
                                    onChange={(e) => setIssueEnableExpiry(e.target.checked)}
                                    label={translate('enable_reward_expiry')}
                                    tooltip={translate('enable_reward_expiry_tooltip')}
                                    marginTop='ecre-mt-2'
                                />
                            </div>

                            {/* Coupon validity days */}
                            {issueEnableExpiry && (
                                <div className="form-group ecre-mb-4">
                                    <Input
                                        id="issue_reward_coupon_validity"
                                        label={translate('reward_coupon_validity')}
                                        tooltip={translate('reward_coupon_validity_tooltip')}
                                        type="number"
                                        value={issueValidityDays || ''}
                                        onChange={(e) => setIssueValidityDays(e.target.value)}
                                        marginTop='ecre-mt-2'
                                        width='100%'
                                        min="1"
                                    />
                                </div>
                            )}

                            {/* Limit coupon usage switcher */}
                            <div className="form-group ecre-mb-4">
                                <Switcher
                                    id="issue_limit_reward_coupon_usage"
                                    checked={issueEnableUsageLimit}
                                    onChange={(e) => setIssueEnableUsageLimit(e.target.checked)}
                                    label={translate('reward_coupon_usage_limit')}
                                    tooltip={translate('reward_coupon_usage_limit_tooltip')}
                                    marginTop='ecre-mt-2'
                                />
                            </div>

                            {/* Usage limit */}
                            {issueEnableUsageLimit && (
                                <div className="form-group ecre-mb-4">
                                    <Input
                                        id="issue_coupon_usage_limit"
                                        label={translate('how_many_times_coupon_used')}
                                        tooltip={translate('reward_coupon_usages_limit')}
                                        type="number"
                                        value={issueUsageLimit || ''}
                                        onChange={(e) => setIssueUsageLimit(e.target.value)}
                                        marginTop='ecre-mt-2'
                                        width='100%'
                                        min="1"
                                    />
                                </div>
                            )}

                            {/* Minimum purchase amount */}
                            <div className="form-group ecre-mb-8">
                                <Input
                                    id="issue_minimum_purchase_amount"
                                    label={`${translate('min_purchase_reward_coupon')} (${currency})`}
                                    tooltip={translate('min_purchase_reward_tooltip')}
                                    type="number"
                                    value={issueMinimumPurchase || ''}
                                    onChange={(e) => setIssueMinimumPurchase(e.target.value)}
                                    width='100%'
                                    min="0"
                                />
                            </div>

                        </>
                    ),
                    footer: (
                        <div className="btn-box ecre-flex ecre-flex-wrap ecre-justify-end ecre-items-center ecre-gap-2">
                            <button
                                onClick={handleIssueRewardCouponToggleModal}
                                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"
                            >
                                {translate('cancel')}
                            </button>
                            <button
                                onClick={handleIssueRewardCoupon}
                                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"
                            >
                                {translate('reward_coupons_create_reward')}
                            </button>
                        </div>
                    )
                }}
            </Modal>


            {/* Reset Confirmation Modal - Fixed */}
            <Modal openModal={isOpenResetModal} toggleModal={() => setIsOpenResetModal(false)}>
                {{
                    header: <div className="title ecre-text-gray-900 ecre-text-base ecre-font-semibold">{translate('do_you_want_to_reset')}</div>,
                    body: (
                        <div className="description">
                            <div className="ecre-text-gray-900 ecre-text-sm ecre-font-normal ecre-mb-4">
                                {translate('custom_reward_settings_lost')}
                            </div>
                            <div className="ecre-text-gray-900 ecre-text-sm ecre-font-normal">
                                {translate('are_you_sure_proceed')}
                            </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('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('reset')}
                            </button>
                        </div>
                    )
                }}
            </Modal>

        </div>
    );
}

export default RewardCoupons;