import React, { useContext, useState } from 'react';
import { FrontendContext } from '../App/FrontendContext';
import Loader from '../../components/core/Loader';
import ecreIcons from '../../components/core/icons';
import { translate } from '../../Helper';

function RewardPointsTable() {
    const { settings, loadingSettings, loadingRewardPoints, rewardpoints } = useContext(FrontendContext);

    if (loadingSettings && loadingRewardPoints) {
        return <Loader />;
    }

    const [currentPage, setCurrentPage] = useState(1);
    const [sortConfig, setSortConfig] = useState({ key: 'id', direction: 'dec' });
    const itemsPerPage = 10;

    // Ensure rewardpoints is an array before proceeding
    const validRewardPoints = Array.isArray(rewardpoints) ? rewardpoints : [];

    // Sorting function
    const sortedPoints = [...validRewardPoints].sort((a, b) => {
        if (a[sortConfig.key] < b[sortConfig.key]) {
            return sortConfig.direction === 'asc' ? -1 : 1;
        }
        if (a[sortConfig.key] > b[sortConfig.key]) {
            return sortConfig.direction === 'asc' ? 1 : -1;
        }
        return 0;
    });

    // Helper function to format the date
    const formatDate = (dateString) => {
        const options = { year: 'numeric', month: 'short', day: 'numeric' };
        return new Date(dateString).toLocaleDateString(undefined, options);
    };

    // Calculate total pages
    const totalPages = Math.ceil(sortedPoints.length / itemsPerPage);

    // Get current items
    const indexOfLastItem = currentPage * itemsPerPage;
    const indexOfFirstItem = indexOfLastItem - itemsPerPage;
    const currentItems = sortedPoints.slice(indexOfFirstItem, indexOfLastItem);

    const handleClick = (event) => {
        setCurrentPage(Number(event.target.id));
    };

    const handleSort = (key) => {
        let direction = 'asc';
        if (sortConfig.key === key && sortConfig.direction === 'asc') {
            direction = 'desc';
        }
        setSortConfig({ key, direction });
    };

    const renderPageNumbers = [];
    if (totalPages <= 3) {
        // If total pages are less than or equal to 3, show all page numbers
        for (let i = 1; i <= totalPages; i++) {
            renderPageNumbers.push(
                <button
                    key={i}
                    id={i}
                    onClick={handleClick}
                    className={`ecre-h-8 ecre-min-w-8 ecre-p-1 ecre-cursor-pointer ecre-border-0 ecre-border-solid !ecre-shadow-none !ecre-outline-none ecre-border-l ecre-rounded-none !ecre-border-[#e0e0e0] ecre-justify-center ecre-items-center ecre-inline-flex ecre-text-sm ecre-font-normal ecre-leading-[21px] hover:!ecre-bg-[#6a40d5] hover:ecre-text-white ${currentPage === i ? '!ecre-bg-[#6a40d5] ecre-text-white' : '!ecre-bg-transparent ecre-text-[#1e1e1e]'}`}
                >
                    {i}
                </button>
            );
        }
    } else {
        // If total pages are more than 3, show Previous 3 pages or the relevant range
        if (currentPage > 1) {
            renderPageNumbers.push(
                <button
                    key={currentPage - 1}
                    id={currentPage - 1}
                    onClick={handleClick}
                    className={`ecre-h-8 ecre-min-w-8 ecre-p-1 ecre-cursor-pointer ecre-border-0 ecre-border-solid !ecre-shadow-none !ecre-outline-none ecre-border-l ecre-rounded-none !ecre-border-[#e0e0e0] ecre-justify-center ecre-items-center ecre-inline-flex ecre-text-sm ecre-font-normal ecre-leading-[21px] hover:!ecre-bg-[#6a40d5] hover:ecre-text-white ${currentPage === currentPage - 1 ? '!ecre-bg-[#6a40d5] ecre-text-white' : '!ecre-bg-transparent ecre-text-[#1e1e1e]'}`}
                >
                    {currentPage - 1}
                </button>
            );
        }
        renderPageNumbers.push(
            <button
                key={currentPage}
                id={currentPage}
                onClick={handleClick}
                className={`ecre-h-8 ecre-min-w-8 ecre-p-1 ecre-cursor-pointer ecre-border-0 ecre-border-solid !ecre-shadow-none !ecre-outline-none ecre-border-l ecre-rounded-none !ecre-border-[#e0e0e0] ecre-justify-center ecre-items-center ecre-inline-flex ecre-text-sm ecre-font-normal ecre-leading-[21px] hover:!ecre-bg-[#6a40d5] hover:ecre-text-white ${currentPage === currentPage ? '!ecre-bg-[#6a40d5] ecre-text-white' : '!ecre-bg-transparent ecre-text-[#1e1e1e]'}`}
            >
                {currentPage}
            </button>
        );
        if (currentPage < totalPages) {
            renderPageNumbers.push(
                <button
                    key={currentPage + 1}
                    id={currentPage + 1}
                    onClick={handleClick}
                    className={`ecre-h-8 ecre-min-w-8 ecre-p-1 ecre-cursor-pointer ecre-border-0 ecre-border-solid !ecre-shadow-none !ecre-outline-none ecre-border-l ecre-rounded-none !ecre-border-[#e0e0e0] ecre-justify-center ecre-items-center ecre-inline-flex ecre-text-sm ecre-font-normal ecre-leading-[21px] hover:!ecre-bg-[#6a40d5] hover:ecre-text-white ${currentPage === currentPage + 1 ? '!ecre-bg-[#6a40d5] ecre-text-white' : '!ecre-bg-transparent ecre-text-[#1e1e1e]'}`}
                >
                    {currentPage + 1}
                </button>
            );
        }
        
        if (currentPage < totalPages - 1) {
            renderPageNumbers.push(<span key="ellipsis" className="ecre-h-8 ecre-min-w-8 ecre-p-1 ecre-cursor-pointer ecre-border-0 ecre-border-solid !ecre-shadow-none !ecre-outline-none ecre-border-l ecre-rounded-none !ecre-border-[#e0e0e0] ecre-justify-center ecre-items-center ecre-inline-flex ecre-text-sm ecre-font-normal ecre-leading-[21px] hover:!ecre-bg-[#6a40d5] hover:ecre-text-white">...</span>);
            renderPageNumbers.push(
                <button
                    key={totalPages}
                    id={totalPages}
                    onClick={handleClick}
                    className={`ecre-h-8 ecre-min-w-8 ecre-p-1 ecre-cursor-pointer ecre-border-0 ecre-border-solid !ecre-shadow-none !ecre-outline-none ecre-border-l ecre-rounded-none !ecre-border-[#e0e0e0] ecre-justify-center ecre-items-center ecre-inline-flex ecre-text-sm ecre-font-normal ecre-leading-[21px] hover:!ecre-bg-[#6a40d5] hover:ecre-text-white ${currentPage === totalPages ? '!ecre-bg-[#6a40d5] ecre-text-white' : '!ecre-bg-transparent ecre-text-[#1e1e1e]'}`}
                >
                    {totalPages}
                </button>
            );
        }
    }

    return (
        <div className="rewards-invites__reward">

            {ecreFrontend.is_user_logged_in ? (
                (settings.canRefferOthers && ecreFrontend.has_orders) || !settings.canRefferOthers ? (
                    <>

                        <div className="ecre-flex ecre-flex-wrap sm:!ecre-flex-nowrap ecre-gap-5 ecre-mb-5">
                            <div className="title-wrap">
                                <h4 className="ecre-text-neutral-950 ecre-text-[25px] ecre-font-medium !ecre-mb-[14px]"> {translate('your_point_rewards')}</h4>
                                <div className="ecre-text-zinc-500 ecre-text-sm ecre-font-normal">{translate('reward_points_earned')}</div>
                            </div>
                        </div>
                        <div className="ecre-relative ecre-overflow-x-auto ecre-mb-8">
                            <table className="!ecre-w-full !ecre-border-spacing-0 !ecre-text-zinc-600 !ecre-mb-0 !ecre-text-xs sm:!ecre-text-sm !ecre-font-normal !ecre-border-separate !ecre-border !ecre-border-solid !ecre-border-zinc-500 !ecre-rounded-[5px] !ecre-overflow-hidden">
                                <thead className="!ecre-bg-zinc-500 ecre-text-left">
                                    <tr>
                                        <th
                                            className="ecre-bg-transparent ecre-text-white ecre-font-semibold !ecre-px-3 !ecre-py-3 sm:!ecre-px-5 sm:!ecre-py-5 !ecre-border-none ecre-cursor-pointer"
                                            onClick={() => handleSort('reward_points')}
                                        >
                                           {translate('reward_points')} {sortConfig.key === 'reward_points' ? (sortConfig.direction === 'asc' ? '▲' : '▼') : ''}
                                        </th>
                                        <th
                                            className="ecre-bg-transparent ecre-text-white ecre-font-semibold !ecre-px-3 !ecre-py-3 sm:!ecre-px-5 sm:!ecre-py-5 !ecre-border-none ecre-cursor-pointer"
                                            onClick={() => handleSort('points')}
                                        >
                                            {translate('points_upper')} {sortConfig.key === 'points' ? (sortConfig.direction === 'asc' ? '▲' : '▼') : ''}
                                        </th>
                                        <th
                                            className="ecre-bg-transparent ecre-text-white ecre-font-semibold !ecre-px-3 !ecre-py-3 sm:!ecre-px-5 sm:!ecre-py-5 !ecre-border-none ecre-cursor-pointer"
                                            onClick={() => handleSort('earned_date')}
                                        >
                                            {translate('earned_date')} {sortConfig.key === 'earned_date' ? (sortConfig.direction === 'asc' ? '▲' : '▼') : ''}
                                        </th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {validRewardPoints.length > 0 ? currentItems.map(point => (
                                        <tr key={point.id}>
                                            <td className="!ecre-px-3 !ecre-py-3 sm:!ecre-px-5 sm:!ecre-py-5 !ecre-border-none">{translate('reward_points')}</td>
                                            <td className="!ecre-px-3 !ecre-py-3 sm:!ecre-px-5 sm:!ecre-py-5 !ecre-border-none">{point.points}</td>
                                            <td className="!ecre-px-3 !ecre-py-3 sm:!ecre-px-5 sm:!ecre-py-5 !ecre-border-none">{formatDate(point.earned_date)}</td>
                            
                                        </tr>
                                    )) : (
                                        <tr>
                                            <td colSpan="4" className="!ecre-px-3 !ecre-py-3 sm:!ecre-px-5 sm:!ecre-py-5 !ecre-border-none ecre-text-center">{translate('no_reward_points')}</td>
                                        </tr>
                                    )}
                                </tbody>
                            </table>
                            {totalPages > 1 && (
                                <div className="ecre-flex ecre-justify-end ecre-mt-4">
                                    <div className="ecre-pagination ecre-ml-auto ecre-rounded-sm ecre-border ecre-border-solid ecre-leading-[1] ecre-border-[#e0e0e0]">
                                        <button
                                            onClick={() => setCurrentPage(currentPage > 1 ? currentPage - 1 : 1)}
                                            className={`ecre-h-8 ecre-min-w-8 ecre-px-3 ecre-border-0 !ecre-shadow-none !ecre-outline-none ecre-rounded-none ecre-justify-center ecre-items-center ecre-inline-flex !ecre-text-[#1e1e1e] ecre-text-sm ecre-font-normal ecre-leading-[21px] hover:!ecre-text-[#1e1e1e] !ecre-bg-transparent ${currentPage === 1 ? 'ecre-opacity-50 ecre-cursor-default' : ' ecre-opacity-100 ecre-cursor-pointer'}`}
                                            disabled={currentPage === 1}
                                        >
                                            {translate('previous')}
                                        </button>
                                        {renderPageNumbers}
                                        <button
                                            onClick={() => setCurrentPage(currentPage < totalPages ? currentPage + 1 : totalPages)}
                                            className={`ecre-h-8 ecre-min-w-8 ecre-px-3 ecre-border-0 ecre-border-solid !ecre-shadow-none !ecre-outline-none ecre-border-l ecre-rounded-none !ecre-border-[#e0e0e0] ecre-justify-center ecre-items-center ecre-inline-flex !ecre-text-[#1e1e1e] ecre-text-sm ecre-font-normal ecre-leading-[21px] hover:!ecre-text-[#1e1e1e] !ecre-bg-transparent ${currentPage === totalPages ? 'ecre-opacity-50 ecre-cursor-default' : ' ecre-opacity-100 ecre-cursor-pointer'}`}
                                            disabled={currentPage === totalPages}
                                        >
                                            {translate('next')}
                                        </button>
                                    </div>
                                </div>
                            )}
                        </div>

                    </>
                ) : (
                    <div className="ecre-mt-6">
                        <div className="icon ecre-flex ecre-justify-center ecre-mb-4">
                            {ecreIcons.noOrder}
                        </div>
                        <div className="ecre-text-[#5e656a] ecre-text-xs ecre-font-normal ecre-leading-[18px]">
                            <p className='ecre-text-center'>{settings.noOrderMessageToReferrer}</p>
                        </div>
                    </div>
                )
            ) : (
                <div>
                    <h3 className="ecre-text-neutral-950 ecre-text-[35px] !ecre-mt-0 ecre-font-medium ecre-mb-2">{translate('refer_and_win_exciting_rewards')}</h3>
                    <p className="ecre-text-[#686977] ecre-mb-5 ecre-text-xs ecre-font-normal">{translate('create_account_get_referral_code')}</p>
                    <button className="ecre-px-2.5 ecre-inline-flex ecre-items-center !ecre-shadow-none ecre-py-2.5 !ecre-bg-[#6d3ae6] ecre-rounded-[5px] ecre-text-white ecre-text-[10px] ecre-font-normal ecre-leading-[15px] ecre-transition hover:!ecre-bg-violet-800"
                        onClick={() => {
                            const siteUrl = ecreFrontend.site_url;
                            window.location.href = `${siteUrl}/my-account/`;
                        }}
                    >
                        <span className="icon ecre-mr-1">
                            {ecreIcons.loginGift}
                        </span>
                        {translate('get_rewards_now')}
                    </button>
                </div>
            )}

        </div>
    );
}

export default RewardPointsTable;