import Image from 'next/image'
import { useState, useEffect, useMemo } from 'react';
import Search from './Search';
import styles from "./table.module.css"
import TableHead from './TableHead';
import TablePaginate from './TablePaginate';
import Link from 'next/link';
import api from '../../../helper/axiosconfig';



function TablePool() {

    const heading = [

        {title: "S/N"},
        {title: "Category"},
        {title: "Round"},
        {title: "Winner"},
        {title: "Winner's Score"},
        {title: "Loser"},
        {title: "Loser's Score"},
        {title: "Updated"},
    ]


    //TablePool Data
    const [players, setPlayers] = useState(null);

    //Search and Sorting through the table
    const [search, setSearch] = useState("");
    const [loading, setLoading] = useState(false);

    //Pagination
    const [totalItems, setTotalItems] = useState(0);
    const [currentPage, setCurrentPage] = useState(1);
    const [itemsOffset, setItemsOffset] = useState({
        initialOffset: 0,
        totalOffset: 0,
    });


    const itemsPerPage = 20;

    const convertDate = (date) => {
        const originalDate = new Date(date);
        const formattedDate = originalDate.toISOString().replace('T', ' @ ').replace(/\.\d{3}Z$/, '');
        return formattedDate
    }

    //Get the data
    useEffect(() => {

        const getResults = async () => {

            //fetch the results
            setLoading(true);
            try {
                const response = await api.get("/result/all");
                setPlayers(response.data);
            } catch(err) {
                console.log(err);
            } finally {
                setLoading(false);
            }
            
        }

        getResults();
    }, []);

    

    



    //Return New Set of Players
    const playerData = useMemo(() => {

        let computedPlayers = players;

        //Filter the table data based on user search.
        if(search){
            computedPlayers = computedPlayers?.filter(
                player => 
                    player.category.toLowerCase().includes(search.toLowerCase()) ||
                    player.round.toLowerCase().includes(search.toLowerCase()) ||
                    player.winner.toLowerCase().includes(search.toLowerCase()) ||
                    player.loser.toLowerCase().includes(search.toLowerCase()) 
                )
        }
        
        
        setTotalItems(computedPlayers?.length);
        setItemsOffset(prevData => {
            return {
                    ...prevData,
                initialOffset: (currentPage - 1) * itemsPerPage + 1, 
                totalOffset: (currentPage - 1) * itemsPerPage + itemsPerPage
            }
        });

        return computedPlayers?.slice(
                (currentPage - 1) * itemsPerPage, 
                (currentPage - 1) * itemsPerPage + itemsPerPage
            );
    }, [players, currentPage, search]);

    

      const searchStyle = {
        container: "justify-end items-end",
        inputContainer: "",
        inputBox: "w-80 rounded-lg",
        placeholder: "Search for results",
    };

 


    return (
            <>
                {
                    loading ? 

                    <div className="flex justify-center items-center flex-col my-40">
                        <div className="w-8 h-8 border-2 border-[#817f7fe7] p-8 animate-spin rounded-full"></div>
                        <p className="text-white text-sm font-medium my-5">Loading...</p>
                    </div>

                    :

                    <div className="flex flex-col items-center">
                        <div className="flex flex-col items-center">
                            <h3 className="text-xl lg:text-3xl text-white font-bold">Result Submission Pool</h3>
                        </div>
                        <div className={`bg-black border-2 border-solid border-secondary p-6 my-10 w-full lg:max-w-[80%] lg:mx-auto overflow-x-auto relative shadow-lg shadow-secondary sm:rounded-lg`}>
                            
                            <Search 
                                handleSearch={
                                    (value) => {
                                        setSearch(value);
                                        setCurrentPage(1);
                                    }

                                }
                                searchStyle={searchStyle}
                                
                                />

                            {playerData ?

                                <table className="w-full text-sm text-left text-gray-500 dark:text-gray-400">
                                    <TableHead heads={heading}/>
                                        <tbody>
                                            
                                            { playerData.map((player, i) => (
                                                <tr key={i} className={`${i % 2 === 0 ? styles.table_body_even : styles.table_body_odd } `}>
                                                    <td className="py-6 px-4 text-primary text-center">
                                                        {player.id}.
                                                    </td>
                                                   
                                                    <td className="py-6 px-4 text-primary text-center">
                                                        {player.category}
                                                    </td>

                                                    <td className="py-6 px-4 text-primary text-center">
                                                        {player.round}
                                                    </td>

                                                    <td className="py-6 px-4 text-primary flex items-center gap-2">
                                                        <i className="ri-check-line bg-[rgba(0,255,0,0.8)] text-primary py-.5 px-1 mx-2 text-sm font-bold rounded-full"></i>
                                                        <span className="text-primary">{player.winner}</span>
                                                    </td>

                                                    <td className="py-6 px-4 text-primary text-center">
                                                        {player.winner_score}
                                                    </td>

                                                    <td className="py-6 px-4 text-primary flex items-center gap-2">
                                                        <i className="ri-close-line bg-[rgb(255,78,78)] text-primary py-.5 px-1 mx-2 text-sm font-bold rounded-full"></i>
                                                        <span className="text-primary">{player.loser}</span>
                                                    </td>


                                                    <td className="py-6 px-4 text-primary text-center">
                                                        {player.loser_score}
                                                    </td>

                                                    <td className="py-6 px-4 text-primary text-center">
                                                        {convertDate(player.updatedAt)}
                                                    </td>
                                                   
                                                </tr>
                                            ))
                                            }
                                            
                                        </tbody>
                                </table>

                            :
                                            
                                    playerData?.length == 0 &&
                                    <div className=" flex justify-center items-center w-full bg-white p-6">
                                            <span className="w-full text-[#e24949] font-semibold text-center text-lg lg:text-xl">No Player Found!</span>
                                    </div>

                            }

                            {/* Pagination */}
                            <nav className="flex justify-start lg:flex-row flex-col lg:justify-between items-start lg:items-center py-6 px-4 text-white bg-siteblue shadow-md shadow-deep" aria-label="TablePool navigation">
                                
                                <span className="text-sm font-normal text-lightash">Showing <span className="font-semibold text-gray-900 dark:text-white">{itemsOffset.initialOffset} - {itemsOffset.totalOffset > totalItems ? totalItems : itemsOffset.totalOffset}</span> of <span className="font-semibold text-gray-900 dark:text-white">{totalItems}</span></span>


                                <TablePaginate
                                    total={totalItems}
                                    itemsPerPage={itemsPerPage}
                                    currentPage={currentPage}
                                    onPageChange={page => setCurrentPage(page)}
                                />
                            


                            </nav>
                        </div>

                    </div>

                }
            </>

        )

}

export default TablePool