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 CustomizedPill from '../../../components/core/CustomizedPill';
import Modal from '../../../components/core/Modal';
import Pagination from '../Pagination';
import RewardPointsRow from './RewardPointsRow';
import Input from '../fields/Input';
import Switcher from '../fields/Switcher';
import axios from 'axios';
import { useUserRewardSettings } from '../../hooks/useUserRewardSettings';
import { displayProPopup, translate } from '../../../Helper';

const RewardPoints = () => {
    const { selectedReferrer, formData, isPro, currency } = useContext(SettingsContext);


    // Use the shared hook
    const {
        userCustomSettings,
        hasCustomSettings,
        globalSettings,
        settingsLoading,
        fetchUserCustomSettings,
        saveUserCustomSettings,
        resetToDefaultSettings
    } = useUserRewardSettings(formData);

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

    // Data fetching states
    const [loading, setLoading] = useState(true); // Start as true for initial load
    const [isPaginating, setIsPaginating] = useState(false); // Track pagination separately
    const [rewardPoints, setRewardPoints] = useState([]);
    const [paginationInfo, setPaginationInfo] = useState({
        current_page: 1,
        per_page: 10,
        total_items: 0,
        total_pages: 0,
        has_more: false
    });

    // Original states
    const [currentPage, setCurrentPage] = useState(1);
    const [itemsPerPage, setItemsPerPage] = useState(10);
    const [timeFilter, setTimeFilter] = useState('All Time');
    const [isOpen, setIsOpen] = useState(false);
    const [isOpenRewardPoints, setIsOpenRewardPoints] = useState(false);
    const [isOpenIssueRewardPoints, setIsOpenIssueRewardPoints] = useState(false);
    // Add this with your other state declarations  
    const [isOpenResetModal, setIsOpenResetModal] = useState(false);


    // Custom settings form states

    const [customRewardPoint, setCustomRewardPoint] = useState(5);
    const [enableRedeemLimit, setEnableRedeemLimit] = useState(true);
    const [customRedeemLimit, setCustomRedeemLimit] = useState('');
    const [issuePointsValue, setIssuePointsValue] = useState(5);


    // Add this new function after the existing fetchRewardPoints function
    const fetchUserPointsSummary = async () => {
        if (!selectedReferrer || !selectedReferrer.user_id) {
            return;
        }

        try {
            const formData = new FormData();
            formData.append('action', 'ecre_fetch_user_points_summary');
            formData.append('nonce', ecreAdmin.nonce);
            formData.append('user_id', selectedReferrer.user_id);

            const response = await axios.post(ecreAdmin.ajaxurl, formData, {
                headers: { 'Content-Type': 'multipart/form-data' },
            });

            if (response.data.success) {
                setUserPointsSummary(response.data.data);
            }
        } catch (error) {
            console.error('Error fetching user points summary:', error);
        }
    };

    // Add this state for user points summary
    const [userPointsSummary, setUserPointsSummary] = useState({
        total_points: 0,
        available_points: 0,
        applied_points: 0,
        expiry_date: '',
        expiry_status: ''
    });

    // Fetch reward points data
    const fetchRewardPoints = 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_points');
            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, {
                headers: { 'Content-Type': 'multipart/form-data' },
            });

            if (response.data.success) {
                setRewardPoints(response.data.data.reward_points || []);
                setPaginationInfo(response.data.data.pagination || {});
            } else {
                setRewardPoints([]);
                setPaginationInfo({
                    current_page: 1,
                    per_page: 10,
                    total_items: 0,
                    total_pages: 0,
                    has_more: false
                });
            }
        } catch (error) {
            console.error('Error fetching reward points:', error);
            setRewardPoints([]);
        } finally {
            setLoading(false);
            setIsPaginating(false);
        }
    };

    // REPLACE the existing fetch function
    const loadUserSettings = async () => {
        if (!selectedReferrer || !selectedReferrer.user_id) {
            setSettingsInitialLoading(false);
            return;
        }

        setSettingsInitialLoading(true);
        const result = await fetchUserCustomSettings(selectedReferrer.user_id);
        if (result) {
            // Set form values using the helper method
            setCustomRewardPoint(result.getEffectiveValue('rewardPoint', 5));
            setCustomRedeemLimit(result.getEffectiveValue('redeemLimit', ''));
            setEnableRedeemLimit(result.getEffectiveValue('enableRedeemLimit', true));
        }
        setSettingsInitialLoading(false);
    };

    // REPLACE the existing save function
    const handleSaveSettings = async () => {
        if (!selectedReferrer || !selectedReferrer.user_id) return;

        const settings = {
            rewardPoint: customRewardPoint,
            enableRedeemLimit: enableRedeemLimit ? 1 : 0
        };

        // Only include redeemLimit if enabled and has value
        if (enableRedeemLimit && customRedeemLimit > 0) {
            settings.redeemLimit = customRedeemLimit;
        }

        const result = await saveUserCustomSettings(selectedReferrer.user_id, settings);
        if (result.success) {
            setIsOpenRewardPoints(false);
            // Refresh other data
            fetchUserPointsSummary();
        } else {
            console.error('Failed to save settings:', result.error);
        }
    };

    // REPLACE the existing reset function
    const handleResetSettings = async () => {
        if (!selectedReferrer || !selectedReferrer.user_id) return;

        const result = await resetToDefaultSettings(selectedReferrer.user_id);
        if (result.success) {
            // Reset form to formData values
            setCustomRewardPoint(formData.rewardPoint || 5);
            setCustomRedeemLimit(formData.redeemLimit || '');
            setEnableRedeemLimit(formData.enableRedeemLimit !== undefined ? formData.enableRedeemLimit : true);
            fetchUserPointsSummary();
        } else {
            console.error('Failed to reset settings:', result.error);
        }
    };

    // NEW FUNCTION - Issue reward points
    const issueRewardPoints = async () => {
        if (!selectedReferrer || !selectedReferrer.user_id || !issuePointsValue) return;

        //setLoading(true);
        try {
            const issueData = new FormData();
            issueData.append('action', 'ecre_issue_reward_points');
            issueData.append('nonce', ecreAdmin.nonce);
            issueData.append('user_id', selectedReferrer.user_id);
            issueData.append('points', issuePointsValue);

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

            if (response.data.success) {
                setIsOpenIssueRewardPoints(false);
                setIssuePointsValue(5);

                // Refresh data
                fetchRewardPoints();
                fetchUserPointsSummary();
            } else {
                console.error('Failed to issue points:', response.data.data);
            }
        } catch (error) {
            console.error('Error issuing points:', error);
        } finally {
            // setLoading(false);
        }
    };

    // REPLACE your existing getRewardPointsText function with this UPDATED version
    const getRewardPointsText = () => {
        // 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

        // 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;
            }

            return rewardTypeValue;
        })();

        // Check if reward type is NOT reward_point - return appropriate warning message
        if (effectiveRewardType !== 'reward_point') {
            // If user has custom settings and the custom reward type is not reward_point
            if (hasCustomSettings) {
                return translate('custom_coupon_settings_warning_message');
            } else {
                // If it's a global setting issue
                return translate('reward_coupons_warning_message');
            }
        }

        // Normal reward points text when reward type is reward_point
        if (hasCustomSettings) {
            const points = userCustomSettings.rewardPoint || customRewardPoint;
            return `${translate('gets_points_per_referral')} ${points} ${translate('points_per_referral')}`;
        } else {
            return `${translate('gets_points_per_referral')} ${formData?.rewardPoint || 0} ${translate('points_per_referral')} (${translate('for_each_points_gets_discount')} ${formData?.redeemPoint || 0} ${translate('points_gets_discount')} ${currency}${formData?.redeemDiscount || 0} ${translate('discount_text')})`;
        }
    };

    // Add this helper function to check if reward type is NOT reward_point (for hiding the Edit button)
    const isNotRewardPointType = () => {
        // 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';
    };

    // UPDATE existing useEffect - add fetchUserCustomSettings call
    useEffect(() => {
        fetchRewardPoints();
        fetchUserPointsSummary();
        loadUserSettings(); // Use new function name
    }, [selectedReferrer, currentPage, itemsPerPage, timeFilter]);


    // Fetch data when component mounts or dependencies change
    useEffect(() => {
        fetchRewardPoints();
    }, [selectedReferrer, currentPage, itemsPerPage, timeFilter]);

    const handleToggleModal = () => {
        setIsOpen(!isOpen);
    };

    // UPDATE existing function
    const handleRewardPointsToggleModal = () => {
        if (!isOpenRewardPoints) {
            // Don't show loading when opening edit modal - settings are already loaded
            // loadUserSettings(); // Remove this call since settings are already loaded
        }
        setIsOpenRewardPoints(!isOpenRewardPoints);
    };

    const handleIssueRewardPointsToggleModal = () => {
        setIsOpenIssueRewardPoints(!isOpenIssueRewardPoints);
    };

    // Data and pagination logic
    const totalPages = paginationInfo.total_pages;
    const startIndex = (paginationInfo.current_page - 1) * paginationInfo.per_page;
    const endIndex = Math.min(startIndex + paginationInfo.per_page, paginationInfo.total_items);
    const currentData = rewardPoints;
    const totalItems = paginationInfo.total_items;

    // 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';

    return (
        <div className="referrer-details__reward-points">
            {!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('customize_reward_points_customers')}</div>
                    <div className="ecre-max-w-[420px] ecre-text-gray-600 ecre-text-sm ecre-font-normal mx-auto">{translate('upgrade_pro_reward_points')}</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('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">
                        <div className="ecre-flex ecre-justify-between items-center ecre-gap-5">
                            <div className="ecre-text-sm ecre-text-gray-600 ecre-font-medium">{translate('reward_points_colon')}
                                <span className="ecre-text-gray-900 ecre-font-normal ecre-ml-2"> {getRewardPointsText()}</span>
                                {hasCustomSettings && (
                                    <CustomizedPill />
                                )}
                            </div>
                            {!isNotRewardPointType() && (
                                <div onClick={handleRewardPointsToggleModal} className="ecre-text-[#3b71ca] ecre-text-sm ecre-font-medium ecre-cursor-pointer ecre-transition hover:ecre-text-[#6a40d5]">
                                    {translate('edit')}
                                </div>
                            )}
                        </div>

                        <div className="reward-points ecre-p-4 ecre-bg-violet-50 ecre-rounded-lg ecre-mt-6">
                            <ul className="ecre-list-none ecre-p-0 ecre-flex ecre-flex-wrap ecre-justify-evenly ecre-gap-4 ecre-m-0">
                                <li className="ecre-flex ecre-gap-2">
                                    <div className="text">
                                        <div className="number ecre-text-[#5d6265] ecre-text-sm ecre-font-bold">
                                            {userPointsSummary.total_points || 0}
                                        </div>
                                        <div className="ecre-text-[#384046] ecre-text-sm ecre-font-normal">{translate('total_earned_points')}</div>
                                        <div className="ecre-text-[#a49da7] ecre-text-xs ecre-font-normal">{translate('reward_points_earned_so_far')}</div>
                                    </div>
                                </li>
                                <li className="ecre-flex ecre-gap-2">
                                    <div className="icon">
                                        {/* SVG content remains the same */}
                                    </div>
                                    <div className={`text ${formData?.enableRewardPointExpiry && 'unavailable' === userPointsSummary.expiry_status && 'unavailable' === formData?.rewardPointExpiryAction?.value ? 'ecre-opacity-50' : ''}`}>
                                        <div className="number ecre-text-[#6d3ae6] ecre-text-sm ecre-font-bold">
                                            {userPointsSummary.available_points || 0}
                                        </div>
                                        <div className="ecre-text-[#384046] ecre-text-sm ecre-font-normal">{translate('available_points')}</div>
                                        <div className="ecre-text-[#a49da7] ecre-text-xs ecre-font-normal">{translate('reward_points_available_for_use')}</div>
                                    </div>
                                </li>
                                <li className="ecre-flex ecre-gap-2">
                                    <div className="text">
                                        <div className="number ecre-text-[#5d6265] ecre-text-sm ecre-font-bold">
                                            {userPointsSummary.redeemed_points || 0}
                                        </div>
                                        <div className="ecre-text-[#384046] ecre-text-sm ecre-font-normal">{translate('redeemed_points')}</div>
                                        <div className="ecre-text-[#a49da7] ecre-text-xs ecre-font-normal">{translate('reward_points_that_have_been_used')}</div>
                                    </div>
                                </li>
                            </ul>

                            {/* Expiry status notifications */}
                            {formData?.enableRewardPointExpiry && 'available' === userPointsSummary.expiry_status && (
                                <div className="ecre-text-center ecre-mt-4">
                                    <div className="ecre-px-1 ecre-inline-block ecre-ml-auto ecre-mr-auto ecre-py-0.5 ecre-mb-3 ecre-bg-red-50 ecre-rounded ecre-text-[#844848] ecre-text-[14px] ecre-font-normal">
                                        {translate('points_will_be_expired_on')} {userPointsSummary.expiry_date}
                                    </div>
                                </div>
                            )}

                            {formData?.enableRewardPointExpiry && 'expired' === userPointsSummary.expiry_status && (
                                <div className="ecre-text-center ecre-mt-4">
                                    <div className="ecre-px-1 ecre-inline-block ecre-ml-auto ecre-mr-auto ecre-py-0.5 ecre-mb-3 ecre-bg-red-50 ecre-rounded ecre-text-[#844848] ecre-text-[12px] ecre-font-normal">
                                        {translate('reward_points_have_expired')}
                                    </div>
                                </div>
                            )}

                            {formData?.enableRewardPointExpiry && 'unavailable' === userPointsSummary.expiry_status && (
                                <div className="ecre-text-center ecre-mt-4">
                                    <div className="ecre-px-1 ecre-inline-block ecre-ml-auto ecre-mr-auto ecre-py-0.5 ecre-mb-3 ecre-bg-red-50 ecre-rounded ecre-text-[#844848] ecre-text-[12px] ecre-font-normal">
                                        {translate('reward_points_is_unavailable')}
                                    </div>
                                </div>
                            )}

                            {/* Redemption info */}
                            <div className="ecre-text-zinc-700 ecre-text-[12px] ecre-font-normal ecre-text-center ecre-leading-[15px] ecre-mt-4">
                                {translate('redeem_during_checkout_info')} <strong className="ecre-text-[#5257C4] ecre-font-semibold">{currency}{formData?.redeemDiscount || '2'}</strong> {translate('per_points_info')} <strong className="ecre-text-[#D857ED] ecre-font-semibold">{formData?.redeemPoint || '10'} {translate('points_info')}</strong>
                            </div>
                        </div>

                    </div>

                    <div className="filterbar ecre-mb-2">
                        <div className="filterbar ecre-flex ecre-flex-wrap ecre-items-center ecre-gap-2">
                            <SelectPerPagination
                                startIndex={startIndex}
                                endIndex={endIndex}
                                totalItems={totalItems}
                                itemsPerPage={itemsPerPage}
                                onItemsPerPageChange={handleItemsPerPageChange}
                            />

                            <button onClick={handleIssueRewardPointsToggleModal} className="sm: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('issue_reward_points')}
                            </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('clear_filter')}
                                    <span className="icon ecre-ml-1">{ecreIcons.circleClose}</span>
                                </div>
                            </div>
                        )}
                    </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_points_table_header')}
                                    </th>
                                    <th className="ecre-px-5 ecre-py-4 ecre-text-left ecre-text-sm ecre-font-normal ecre-text-gray-600">
                                        {translate('earned_date')}
                                    </th>
                                    <th className="ecre-px-5 ecre-py-4 ecre-text-left ecre-text-sm ecre-font-normal ecre-text-gray-600">
                                        {translate('actions')}
                                    </th>
                                </tr>
                            </thead>
                            <tbody className="ecre-bg-white ecre-divide-y ecre-divide-gray-200">
                                {loading ? (
                                    <tr>
                                        <td colSpan="3" className="ecre-px-5 ecre-py-8 ecre-text-center ecre-text-gray-500">
                                            {translate('loading_reward_points')}
                                        </td>
                                    </tr>
                                ) : currentData.length > 0 ? (
                                    currentData.map((pointEntry, index) => (
                                        <RewardPointsRow
                                            key={pointEntry.id || index}
                                            pointEntry={pointEntry}
                                        />
                                    ))
                                ) : (
                                    <tr>
                                        <td colSpan="3" className="ecre-px-5 ecre-py-8 ecre-text-center ecre-text-gray-500">
                                            {translate('no_reward_points_found')}
                                        </td>
                                    </tr>
                                )}
                            </tbody>
                        </table>
                    </div>

                    {/* Only show pagination when there's data */}
                    {currentData.length > 0 && (
                        <Pagination
                            currentPage={paginationInfo.current_page || currentPage}
                            totalPages={totalPages}
                            onPageChange={handlePageChange}
                        />
                    )}

                </>
            )
            }

            {/* REPLACE the entire existing Customize Reward Points Modal */}
            <Modal className='echorewards-reward-management' openModal={isOpenRewardPoints} toggleModal={handleRewardPointsToggleModal}>
                {{
                    header: <div className="title ecre-text-gray-900 ecre-text-base ecre-font-semibold">{translate('customize_reward_points_options')}</div>,
                    body: (
                        <>


                            {/* UPDATE - Reward points input */}
                            <div className="form-group ecre-mb-4">
                                <Input
                                    id="reward_points_per_referral"
                                    label={translate('reward_points_per_referral')}
                                    tooltip={translate('number_of_points_awarded_per_referral')}
                                    type="number"
                                    value={customRewardPoint || ''} // FIX - Ensure it's never undefined
                                    onChange={(e) => {
                                        const value = e.target.value;
                                        setCustomRewardPoint(value === '' ? '' : parseInt(value) || 0);
                                    }}
                                    width='100%'
                                    min="1"
                                />
                            </div>

                            {/* UPDATE - Redeem limit section */}
                            <div className="form-group ecre-mb-8">
                                <Switcher
                                    id="enable_redeem_limit_points"
                                    checked={enableRedeemLimit}
                                    onChange={(e) => setEnableRedeemLimit(e.target.checked)}
                                    label={translate('redeem_limit_reward_points_per_order')}
                                    tooltip={translate('enable_reward_points_per_order')}
                                    marginTop='ecre-mt-2'
                                />
                                {enableRedeemLimit && (
                                    <Input
                                        id="redeem_limit_points"
                                        label={translate('how_many_reward_points_used_per_order')}
                                        type="number"
                                        value={customRedeemLimit === '' || customRedeemLimit === null ? '' : customRedeemLimit} // FIX
                                        onChange={(e) => {
                                            const value = e.target.value;
                                            setCustomRedeemLimit(value === '' ? '' : parseInt(value) || 0);
                                        }}
                                        marginTop='ecre-mt-2'
                                        width='100%'
                                        min="0"
                                        placeholder={translate('enter_redeem_limit_placeholder')}
                                    />
                                )}
                            </div>
                        </>
                    ),
                    footer: (
                        <div className="btn-box ecre-flex ecre-justify-between ecre-flex-wrap ecre-items-center ecre-gap-4">
                            {/* UPDATE - Reset button with proper state handling */}
                            <button
                                onClick={() => setIsOpenResetModal(true)}
                                disabled={settingsLoading || !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('reset_to_default')}
                            </button>
                            <div className="btn-box ecre-flex ecre-flex-wrap ecre-items-center ecre-gap-2">
                                {/* UPDATE - Cancel button with loading state */}
                                <button
                                    onClick={handleRewardPointsToggleModal}
                                    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('cancel')}
                                </button>
                                {/* UPDATE - Save button with proper function call */}
                                <button
                                    onClick={handleSaveSettings}
                                    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('saving') : translate('save_changes')}
                                </button>
                            </div>
                        </div>
                    )
                }}
            </Modal>

            {/* UPDATE the existing Issue Reward Points Modal */}
            <Modal className='echorewards-reward-management' openModal={isOpenIssueRewardPoints} toggleModal={handleIssueRewardPointsToggleModal}>
                {{
                    header: <div className="title ecre-text-gray-900 ecre-text-base ecre-font-semibold">{translate('issuing_reward_points')}</div>,
                    body: (
                        <>
                            {/* UPDATE - Points input with proper state */}
                            <div className="form-group">
                                <Input
                                    id="reward_discount_points"
                                    label={translate('enter_the_points')}
                                    tooltip={translate('number_of_points_to_issue')}
                                    type="number"
                                    value={issuePointsValue || ''} // FIX - Ensure it's never undefined
                                    onChange={(e) => {
                                        const value = e.target.value;
                                        setIssuePointsValue(value === '' ? 0 : parseInt(value) || 0);
                                    }}
                                    width='100%'
                                    min="1"
                                />
                            </div>
                        </>
                    ),
                    footer: (
                        <div className="btn-box ecre-flex ecre-flex-wrap ecre-justify-end ecre-items-center ecre-gap-2">
                            {/* UPDATE - Cancel button with loading state */}
                            <button
                                onClick={handleIssueRewardPointsToggleModal}
                                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('cancel')}
                            </button>
                            {/* UPDATE - Create button with proper validation and loading */}
                            <button
                                onClick={issueRewardPoints}
                                disabled={settingsLoading || !issuePointsValue}
                                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('creating') : translate('create_reward')}
                            </button>
                        </div>
                    )
                }}
            </Modal>

            {/* Reset Confirmation Modal - Updated */}
            <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={async () => {
                                    await handleResetSettings();
                                    setIsOpenResetModal(false);
                                    setIsOpenRewardPoints(false);
                                }}
                                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 RewardPoints;
