import React, { useContext, useState, useEffect, useMemo } from 'react';
import ecreIcons from '../../components/core/icons';
import { SettingsContext } from '../App/SettingsContext';
import SelectPerPagination from '../components/fields/SelectPerPagination';
import SelectTimeFilter from '../components/fields/SelectTimeFilter';
import SearchInput from '../components/fields/SearchInput';
import FilterDropdown from '../components/fields/FilterDropdown';
import ReferrerRow from '../components/RewardManagement/ReferrerRow';
import Pagination from '../components/Pagination';
import { translate } from '../../Helper';
import axios from 'axios';

const RewardManagement = () => {
    const { handleActiveScreen, setSelectedReferrer, isPro, currency } = useContext(SettingsContext);
    
    // State management
    const [loading, setLoading] = useState(true); // Start as true for initial load
    const [isPaginating, setIsPaginating] = useState(false); // Track pagination separately
    const [referrers, setReferrers] = useState([]); // Only current page data
    const [dashboardSummary, setDashboardSummary] = useState({
        total_referrers: 0,
        total_referrals: 0,
        total_referral_sales: 0,
        total_rewards_issued: 0
    });
    const [currentPage, setCurrentPage] = useState(1);
    const [itemsPerPage, setItemsPerPage] = useState(10);
    const [searchTerm, setSearchTerm] = useState('');
    const [timeFilter, setTimeFilter] = useState('All Time');
    const [showFilterDropdown, setShowFilterDropdown] = useState(false);
    
    // Pagination info from server
    const [paginationInfo, setPaginationInfo] = useState({
        current_page: 1,
        per_page: 10,
        total_items: 0,
        total_pages: 0,
        has_more: false
    });

    // Applied filters
    const [filterCustomers, setFilterCustomers] = useState({
        customRewards: false,
        customReferrals: false
    });
    
    // Temporary filters
    const [tempFilterCustomers, setTempFilterCustomers] = useState({
        customRewards: false,
        customReferrals: false
    });

    // Fetch dashboard summary
    const fetchDashboardSummary = async () => {
        try {
            const formData = new FormData();
            formData.append('action', 'ecre_fetch_dashboard_summary');
            formData.append('nonce', ecreAdmin.nonce);

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

            if (response.data.success) {
                setDashboardSummary(response.data.data);
            } else {
                console.error('Failed to fetch dashboard summary');
            }
        } catch (error) {
            console.error('Error fetching dashboard summary:', error);
        }
    };

    // Fetch referrers with server-side pagination, filtering, and search
    const fetchReferrers = async (page = 1, perPage = 10, search = '', timeFilter = 'All Time', filters = {}, isInitial = false) => {
        if (isInitial) {
            setLoading(true);
        } else {
            setIsPaginating(true);
        }

        try {
            const formData = new FormData();
            formData.append('action', 'ecre_fetch_referrers');
            formData.append('nonce', ecreAdmin.nonce);
            formData.append('page', page);
            formData.append('per_page', perPage);
            formData.append('search', search);
            formData.append('time_filter', timeFilter);
            formData.append('custom_rewards_filter', filters.customRewards ? '1' : '0');
            formData.append('custom_referrals_filter', filters.customReferrals ? '1' : '0');

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

            if (response.data.success) {
                const result = response.data.data;
                setReferrers(result.data);
                setPaginationInfo(result.pagination);
            } else {
                console.error('Failed to fetch referrers');
                setReferrers([]);
            }
        } catch (error) {
            console.error('Error fetching referrers:', error);
            setReferrers([]);
        } finally {
            setLoading(false);
            setIsPaginating(false);
        }
    };

    // Initial data fetch
    useEffect(() => {
        fetchDashboardSummary();
        fetchReferrers(1, itemsPerPage, searchTerm, timeFilter, filterCustomers);
    }, []);

    // Fetch data when filters or pagination changes
    useEffect(() => {
        fetchReferrers(currentPage, itemsPerPage, searchTerm, timeFilter, filterCustomers);
    }, [currentPage, itemsPerPage, searchTerm, timeFilter, filterCustomers]);
    

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

    const handleItemsPerPageChange = (newItemsPerPage) => {
        setItemsPerPage(newItemsPerPage);
        setCurrentPage(1); // Reset to first page when changing items per page
    };

    const handleSearchChange = (newSearchTerm) => {
        setSearchTerm(newSearchTerm);
        setCurrentPage(1); // Reset to first page when searching
    };

    const handleTimeFilterChange = (newTimeFilter) => {
        setTimeFilter(newTimeFilter);
        setCurrentPage(1); // Reset to first page when filtering
    };

    const handleToggleFilterDropdown = () => {
        setShowFilterDropdown(!showFilterDropdown);
        if (!showFilterDropdown) {
            setTempFilterCustomers(filterCustomers);
        }
    };

    const handleTempFilterChange = (filterType, value) => {
        setTempFilterCustomers(prev => ({
            ...prev,
            [filterType]: value
        }));
    };

    // Apply the temporary filters to actual filters
    const applyFilters = () => {
        setFilterCustomers({
            customRewards: tempFilterCustomers.customRewards,
            customReferrals: tempFilterCustomers.customReferrals
        });
        setCurrentPage(1); // Reset to first page when applying filters
        setShowFilterDropdown(false);
    };

    // Reset all filters
    const resetFilters = () => {
        setSearchTerm('');
        setTimeFilter('All Time');
        setCurrentPage(1);
        const resetFiltersObj = {
            customRewards: false,
            customReferrals: false
        };
        setFilterCustomers(resetFiltersObj);
        setTempFilterCustomers(resetFiltersObj);
        setShowFilterDropdown(false);
    };

    // Clear active filters
    const clearFilters = () => {
        const resetFiltersObj = {
            customRewards: false,
            customReferrals: false
        };
        setFilterCustomers(resetFiltersObj);
        setTempFilterCustomers(resetFiltersObj);
        setSearchTerm('');
        setTimeFilter('All Time');
        setCurrentPage(1);
    };

    const hasActiveFilters = filterCustomers.customRewards || 
                            filterCustomers.customReferrals || 
                            searchTerm !== '' || 
                            timeFilter !== 'All Time';

    // Calculate display info
    const startIndex = (currentPage - 1) * itemsPerPage + 1;
    const endIndex = Math.min(startIndex + referrers.length - 1, paginationInfo.total_items);

    return (
        <div className="reward-management-screen">
            <div className="reward-management__summary ecre-mb-8 sm:ecre-mb-10 lg:ecre-mb-14">
                <div className="ecre-text-[#111827] ecre-text-base ecre-font-semibold ecre-mb-4">{ translate( 'quick_summary' ) }</div>
                <div className="ecre-grid ecre-grid-cols-1 sm:ecre-grid-cols-2 ecre-gap-4">
                    <div className="summary-card ecre-p-4 ecre-bg-white ecre-rounded-lg ecre-inline-flex ecre-justify-start ecre-items-center ecre-gap-6">
                        <div className="icon-wrap">
                            {ecreIcons.userGroup}
                        </div>
                        <div className="text-wrapper">
                            <div className="ecre-text-[#111827] ecre-text-sm ecre-font-medium">{ translate( 'total_referrers' ) }</div>
                            <div className="ecre-text-[#111827] ecre-text-xl ecre-font-medium">{dashboardSummary.total_referrers}</div>
                        </div>
                    </div>
                    <div className="summary-card ecre-p-4 ecre-bg-white ecre-rounded-lg ecre-inline-flex ecre-justify-start ecre-items-center ecre-gap-6">
                        <div className="icon-wrap">
                            {ecreIcons.usdDollar}
                        </div>
                        <div className="text-wrapper">
                            <div className="ecre-text-[#111827] ecre-text-sm ecre-font-medium">{ translate( 'total_referral_sales' ) }</div>
                            <div className="ecre-text-[#111827] ecre-text-xl ecre-font-medium">{currency}{dashboardSummary.total_referral_sales}</div>
                        </div>
                    </div>
                    <div className="summary-card ecre-p-4 ecre-bg-white ecre-rounded-lg ecre-inline-flex ecre-justify-start ecre-items-center ecre-gap-6">
                        <div className="icon-wrap">
                            {ecreIcons.refferalsManagement}
                        </div>
                        <div className="text-wrapper">
                            <div className="ecre-text-[#111827] ecre-text-sm ecre-font-medium">{ translate( 'total_referral_coupons' ) }</div>
                            <div className="ecre-text-[#111827] ecre-text-xl ecre-font-medium">{dashboardSummary.total_referrals}</div>
                        </div>
                    </div>
                    <div className="summary-card ecre-p-4 ecre-bg-white ecre-rounded-lg ecre-inline-flex ecre-justify-start ecre-items-center ecre-gap-6">
                        <div className="icon-wrap">
                            {ecreIcons.rewardGift}
                        </div>
                        <div className="text-wrapper">
                            <div className="ecre-text-[#111827] ecre-text-sm ecre-font-medium">{ translate( 'reward_issued' ) }</div>
                            <div className="ecre-text-[#111827] ecre-text-xl ecre-font-medium">{dashboardSummary.total_rewards_issued}</div>
                        </div>
                    </div>
                </div>
            </div>

            <div className="reward-management__referrers">
                <div className="ecre-text-[#111827] ecre-text-base ecre-font-semibold ecre-mb-4">{ translate( 'all_referrers' ) }</div>
                
                <div className="filterbar ecre-mb-2">
                    <div className="ecre-flex ecre-flex-wrap ecre-items-center ecre-gap-2">
                        <SelectPerPagination
                            startIndex={startIndex}
                            endIndex={endIndex}
                            totalItems={paginationInfo.total_items}
                            itemsPerPage={itemsPerPage}
                            onItemsPerPageChange={handleItemsPerPageChange}
                        />

                        <SearchInput
                            searchTerm={searchTerm}
                            onSearchChange={handleSearchChange}
                        />

                        <SelectTimeFilter
                            timeFilter={timeFilter}
                            onTimeFilterChange={handleTimeFilterChange}
                        />

                        <FilterDropdown
                            isOpen={showFilterDropdown}
                            onToggle={handleToggleFilterDropdown}
                            tempFilters={tempFilterCustomers}
                            onTempFilterChange={handleTempFilterChange}
                            onApplyFilters={applyFilters}
                            onResetFilters={resetFilters}
                            isPro={isPro}
                        />
                    </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>

                {loading ? (
                    <div className="ecre-p-8 ecre-text-center">
                        <div className="ecre-inline-block ecre-animate-spin ecre-rounded-full ecre-h-8 ecre-w-8 ecre-border-b-2 ecre-border-blue-600"></div>
                        <p className="ecre-mt-2 ecre-text-gray-600">{ translate( 'loading_referrers' ) }</p>
                    </div>
                ) : (
                    <>
                        <div className="ecre-overflow-x-auto">
                            <table className="ecre-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( 'referrer' ) }
                                        </th>
                                        <th className="ecre-px-5 ecre-py-4 ecre-text-left ecre-text-sm ecre-font-normal ecre-text-gray-600">
                                            { translate( 'referral_history_referrals' ) || 'Referrals' }
                                        </th>
                                        <th className="ecre-px-5 ecre-py-4 ecre-text-left ecre-text-sm ecre-font-normal ecre-text-gray-600">
                                            { translate( 'sales_generated' ) || 'Sales Generated' }
                                        </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">
                                    {referrers.length > 0 ? (
                                        referrers.map((referrer, index) => (
                                            <ReferrerRow
                                                key={referrer.id}
                                                referrer={referrer}
                                                index={index}
                                                startIndex={startIndex - 1}
                                            />
                                        ))
                                    ) : (
                                        <tr>
                                            <td colSpan="4" className="ecre-px-5 ecre-py-8 ecre-text-center ecre-text-gray-500">
                                                { translate( 'no_referrers_found' ) }
                                            </td>
                                        </tr>
                                    )}
                                </tbody>
                            </table>
                        </div>

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

export default RewardManagement;