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 Avatar from '../../images/avatar.png';
import axios from 'axios';

const RewardManagement = () => {
    const { handleActiveScreen } = useContext(SettingsContext);
    const [loading, setLoading] = useState(false);
    const [referrer_list, setReferrers] = useState([]);



    // Sample data
    const SAMPLE_REFERRERS = [
        {
            id: 1,
            name: "Alan Marphy",
            email: "alan.marphy@email.com",
            referrals: 245,
            salesGenerated: 12450,
            avatar: Avatar,
            hasCustomRewards: true,
            hasCustomReferrals: true,
            joinDate: new Date('2024-02-15'),
            lastActivity: new Date('2025-08-01')
        },
        {
            id: 2,
            name: "Myra Liuer",
            email: "myra.liuer@company.com",
            referrals: 189,
            salesGenerated: 8750,
            avatar: null,
            hasCustomRewards: true,
            hasCustomReferrals: false,
            joinDate: new Date('2024-03-22'),
            lastActivity: new Date('2025-07-28')
        },
        {
            id: 3,
            name: "Sikved Jonnes",
            email: "s.jonnes@business.org",
            referrals: 156,
            salesGenerated: 6890,
            avatar: Avatar,
            hasCustomRewards: false,
            hasCustomReferrals: true,
            joinDate: new Date('2023-11-08'),
            lastActivity: new Date('2025-08-05')
        },
        {
            id: 4,
            name: "John Doe",
            email: "john.doe@gmail.com",
            referrals: 134,
            salesGenerated: 3450,
            avatar: Avatar,
            hasCustomRewards: true,
            hasCustomReferrals: true,
            joinDate: new Date('2024-01-10'),
            lastActivity: new Date('2025-06-15')
        },
        {
            id: 5,
            name: "Sarah Wilson",
            email: "sarah.w@startup.io",
            referrals: 298,
            salesGenerated: 15620,
            avatar: Avatar,
            hasCustomRewards: false,
            hasCustomReferrals: false,
            joinDate: new Date('2023-09-14'),
            lastActivity: new Date('2025-08-06')
        },
        {
            id: 6,
            name: "Emma Rodriguez",
            email: "emma.rodriguez@tech.com",
            referrals: 87,
            salesGenerated: 2180,
            avatar: Avatar,
            hasCustomRewards: true,
            hasCustomReferrals: false,
            joinDate: new Date('2024-05-18'),
            lastActivity: new Date('2025-07-22')
        },
        {
            id: 7,
            name: "Michael Chen",
            email: "m.chen@enterprise.net",
            referrals: 312,
            salesGenerated: 18900,
            avatar: Avatar,
            hasCustomRewards: true,
            hasCustomReferrals: true,
            joinDate: new Date('2023-08-03'),
            lastActivity: new Date('2025-08-04')
        },
        {
            id: 8,
            name: "Lisa Thompson",
            email: "lisa.t@marketing.co",
            referrals: 67,
            salesGenerated: 1890,
            avatar: null,
            hasCustomRewards: false,
            hasCustomReferrals: true,
            joinDate: new Date('2024-06-12'),
            lastActivity: new Date('2025-05-30')
        },
        {
            id: 9,
            name: "David Kim",
            email: "david.kim@solutions.biz",
            referrals: 201,
            salesGenerated: 9340,
            avatar: Avatar,
            hasCustomRewards: true,
            hasCustomReferrals: true,
            joinDate: new Date('2024-04-07'),
            lastActivity: new Date('2025-07-18')
        },
        {
            id: 10,
            name: "Rachel Green",
            email: "rachel.green@agency.com",
            referrals: 45,
            salesGenerated: 1120,
            avatar: Avatar,
            hasCustomRewards: false,
            hasCustomReferrals: false,
            joinDate: new Date('2024-07-21'),
            lastActivity: new Date('2025-08-02')
        },
        {
            id: 11,
            name: "Alex Johnson",
            email: "alex.johnson@consulting.org",
            referrals: 178,
            salesGenerated: 7620,
            avatar: null,
            hasCustomRewards: true,
            hasCustomReferrals: false,
            joinDate: new Date('2023-12-15'),
            lastActivity: new Date('2025-07-25')
        },
        {
            id: 12,
            name: "Sophie Miller",
            email: "sophie@creative.studio",
            referrals: 234,
            salesGenerated: 11280,
            avatar: Avatar,
            hasCustomRewards: false,
            hasCustomReferrals: true,
            joinDate: new Date('2024-01-28'),
            lastActivity: new Date('2025-08-03')
        }
    ];

    // Add all states
    const [referrers] = useState(SAMPLE_REFERRERS);
    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);

    // Applied filters (used for actual filtering)
    const [filterCustomers, setFilterCustomers] = useState({
        customRewards: false,
        customReferrals: false
    });
    
    // Temporary filters (used in dropdown, only applied when "Apply Filter" is clicked)
    const [tempFilterCustomers, setTempFilterCustomers] = useState({
        customRewards: false,
        customReferrals: false
    });

    // Helper function to check if date falls within time filter
    const isWithinTimeFilter = (date, filter) => {
        const now = new Date();
        const oneMonthAgo = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate());
        const threeMonthsAgo = new Date(now.getFullYear(), now.getMonth() - 3, now.getDate());
        const sixMonthsAgo = new Date(now.getFullYear(), now.getMonth() - 6, now.getDate());
        const oneYearAgo = new Date(now.getFullYear() - 1, now.getMonth(), now.getDate());

        switch (filter) {
        case '1 Month':
            return date >= oneMonthAgo;
        case '3 Month':
            return date >= threeMonthsAgo;
        case '5 Month':
            return date >= sixMonthsAgo;
        case '1 Year':
            return date >= oneYearAgo;
        case 'All Time':
        default:
            return true;
        }
    };

    // Filter and sort data
    const filteredData = useMemo(() => {
        let filtered = referrers.filter(referrer => {
            // Text search filter
            const matchesSearch = referrer.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                referrer.email.toLowerCase().includes(searchTerm.toLowerCase());
            
            // Custom rewards filter - if checked, ONLY show referrers WITH custom rewards
            let passesRewardsFilter = true;
            if (filterCustomers.customRewards) {
                passesRewardsFilter = referrer.hasCustomRewards === true;
            }
            
            // Custom referrals filter - if checked, ONLY show referrers WITH custom referrals
            let passesReferralsFilter = true;
            if (filterCustomers.customReferrals) {
                passesReferralsFilter = referrer.hasCustomReferrals === true;
            }
            
            // Time filter (based on last activity)
            const matchesTimeFilter = isWithinTimeFilter(referrer.lastActivity, timeFilter);

            return matchesSearch && passesRewardsFilter && passesReferralsFilter && matchesTimeFilter;
        });

        return filtered;
    }, [referrers, searchTerm, filterCustomers, timeFilter]);

    // Pagination
    const totalPages = Math.ceil(filteredData.length / itemsPerPage);
    const startIndex = (currentPage - 1) * itemsPerPage;
    const endIndex = startIndex + itemsPerPage;
    const currentData = filteredData.slice(startIndex, endIndex);

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

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

    const handleToggleFilterDropdown = () => {
        setShowFilterDropdown(!showFilterDropdown);
        // Sync temp filters with applied filters when opening
        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);
        setShowFilterDropdown(false);
    };

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

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

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


    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">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">Total Referrers</div>
                            <div className="ecre-text-[#111827] ecre-text-xl ecre-font-medium">247</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">Total Referral Sales</div>
                            <div className="ecre-text-[#111827] ecre-text-xl ecre-font-medium">247</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">Total Referrals</div>
                            <div className="ecre-text-[#111827] ecre-text-xl ecre-font-medium">247</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">Reward Issued</div>
                            <div className="ecre-text-[#111827] ecre-text-xl ecre-font-medium">247</div>
                        </div>
                    </div>

                </div>
            </div>

            <div className="reward-management__referrers">
                <div className="ecre-text-[#111827] ecre-text-base ecre-font-semibold ecre-mb-4">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={filteredData.length}
                        itemsPerPage={itemsPerPage}
                        onItemsPerPageChange={handleItemsPerPageChange}
                        />

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

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

                        <FilterDropdown
                            isOpen={showFilterDropdown}
                            onToggle={handleToggleFilterDropdown}
                            tempFilters={tempFilterCustomers}
                            onTempFilterChange={handleTempFilterChange}
                            onApplyFilters={applyFilters}
                            onResetFilters={resetFilters}
                        />
                    </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">
                                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">
                                    Referrer
                                </th>
                                <th className="ecre-px-5 ecre-py-4 ecre-text-left ecre-text-sm ecre-font-normal ecre-text-gray-600">
                                    Referrals
                                </th>
                                <th className="ecre-px-5 ecre-py-4 ecre-text-left ecre-text-sm ecre-font-normal ecre-text-gray-600">
                                    Sales Generated
                                </th>
                                <th className="ecre-px-5 ecre-py-4 ecre-text-left ecre-text-sm ecre-font-normal ecre-text-gray-600">
                                    Actions
                                </th>
                            </tr>
                        </thead>
                        <tbody className="ecre-bg-white ecre-divide-y ecre-divide-gray-200">
                        {currentData.map((referrer, index) => (
                            <ReferrerRow
                                key={referrer.id}
                                referrer={referrer}
                                index={index}
                                startIndex={startIndex}
                                handleActiveScreen={()=> handleActiveScreen('referrer_details')}
                            />
                        ))}
                        </tbody>
                    </table>
                </div>

                <Pagination
                    currentPage={currentPage}
                    totalPages={totalPages}
                    onPageChange={handlePageChange}
                />
            </div>
        </div>
    );

}

export default RewardManagement;