import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import moment from "moment";
import { myBetList, profitLoss } from "../../redux/_reducers/_reducers";
import ShowBetsProfitLoss from "../../component/ShowBetsProfitLoss/showbetsprofitloss";
import Loader from "../../component/Loader/Loader";
// import RightSidebar from "../../../components/RightSidebar/RightSidebar";
// import ReactPaginate from "react-paginate";

function ProfitAndLoss() {
    const dispatch = useDispatch();
    const [fromDate, setFromDate] = useState(moment().subtract(7, 'days').unix());
    const [toDate, setToDate] = useState(moment().unix());
    const [page, setPage] = useState(100);
    const [profitLossDataa, setProfitLossDataa] = useState([]);
    const [sports, setSports] = useState(0);
    const [currentPage, setCurrentPage] = useState(0);
    const [isBetpro, SetBetpro] = useState(false)
    const itemsPerPage = page;
    const [betHistoryData, setBetHistoryData] = useState([]);


    const { profitLossData, myBetListData, loading } = useSelector(
        (state) => state.authentication
    );

    const handleSportsChange = (e) => {
        setSports(e.target.value);
    };

    const handleDateChange = (e, type) => {
        const value = e.target.value;
        const unixTimestamp = Math.floor(new Date(value).getTime() / 1000);
        if (type === 'from') {
            setFromDate(unixTimestamp);
        } else if (type === 'to') {
            setToDate(unixTimestamp);
        }
    };

    useEffect(() => {
        if (profitLossData) {
            setProfitLossDataa(profitLossData);
        }
    }, [profitLossData]);
    useEffect(() => {
        if (myBetListData) {
            setBetHistoryData(myBetListData);
        }
    }, [myBetListData]);

    const handlePageNumber = (event) => {
        setPage(event.target.value);
    };



    const handleSubmit = (e) => {
        if (e) e.preventDefault();
        let data =
        {
            "from_date": fromDate,
            "to_date": toDate,
            "limit": page,
            "sport_id": sports,
            "match_id": "0",
            "betType": "P",
            "pageno": 1
        }
        dispatch(profitLoss(data));
    };

    const handleSubmitBets = (ele) => {

        SetBetpro(true)
        let data =
        {
            "from_date": 0,
            "to_date": 0,
            "limit": "100",
            "sport_id": ele?.sport_id,
            "betType": "C",
            "pageno": 1,
            "market_id": "0",
            "match_id": ele?.match_id
        }
        dispatch(myBetList(data));
    };

    const handleClose = () => {
        SetBetpro(false)
        setBetHistoryData({})
    }

    useEffect(() => {
        handleSubmit();
    }, [page]);

    return (
        <>
            {loading && <Loader />}
            <div className="p-2">
                <div className="grid grid-cols-1 md:grid-cols-4 gap-4 bg-white px-2 py-4 rounded shadow-md">
                    <select
                        value={sports}
                        onChange={handleSportsChange}
                        className="p-1 border rounded w-full bg-white">
                        <option value="0">Sports</option>
                        <option value="4">Cricket</option>
                        <option value="2">Tennis</option>
                        <option value="1">Football</option>
                        <option value="111">Casino</option>
                    </select>
                    <input
                        type="date"
                        value={moment.unix(fromDate).format("YYYY-MM-DD")}
                        onChange={(e) => handleDateChange(e, "from")}
                        className="p-1 bg-white  border rounded w-full"
                    />
                    <input
                        type="date"
                        value={moment.unix(toDate).format("YYYY-MM-DD")}
                        onChange={(e) => handleDateChange(e, "to")}
                        className="p-1 bg-white  border rounded w-full"
                    />
                    <button
                        onClick={handleSubmit}
                        className="w-full bg-[var(--light-header)] text-white py-1.5 rounded hover:bg-[var(--secondary)] transition">
                        Search
                    </button>
                </div>

                <div className="mt-4 bg-white border">
                    <div className="border-b">
                        <h4 className="text-md text-white font-semibold bg-[var(--primary)]  rounded p-1.5">Profit/Loss</h4>
                    </div>

                    <div className="text-[16px] flex items-center gap-2 p-4">
                        <p>Show</p>
                        <select
                            value={page}
                            onChange={handlePageNumber}
                            className="border px-2 py-1 bg-white rounded cursor-pointer"
                        >
                            <option value="25">25</option>
                            <option value="50">50</option>
                            <option value="100">100</option>
                        </select>
                        <p>entries</p>
                    </div>

                    <div className="overflow-x-auto px-4 pb-4">
                        <table className="w-full border-collapse border border-gray-200">
                            <thead className="">
                                <tr className="bg-[var(--light-header)] text-white">
                                    <th className="border whitespace-nowrap px-4 py-2">Match</th>
                                    <th className="border whitespace-nowrap px-4 py-2">Stack</th>
                                    <th className="border whitespace-nowrap px-4 py-2">Profit/Loss</th>
                                    <th className="border whitespace-nowrap px-4 py-2">Commission</th>
                                    <th className="border whitespace-nowrap px-4 py-2">Show Bets</th>
                                </tr>
                            </thead>
                            <tbody>
                                {profitLossDataa && profitLossDataa?.length > 0 ? (
                                    profitLossDataa?.map((element, i) => (
                                        <tr key={i} className="text-center">
                                            <td className="border px-4 py-2 whitespace-nowrap">
                                                {element?.sportName} | {element?.seriesName} <br />
                                                {element?.matchName}
                                                <br />
                                                {moment.unix(element.matchDate).format("MMM DD, YYYY HH:MM:SS A")}
                                            </td>
                                            <td className="border px-4 py-2">{element?.stack}</td>
                                            <td
                                                className={`border px-4 py-2 font-semibold ${element?.userPL < 0 ? "text-red-500" : "text-green-500"
                                                    }`}
                                            >
                                                {element?.userPL}
                                            </td>
                                            <td className="border px-4 py-2">{element?.userComm > 0 ? element?.userComm : "0"}</td>
                                            <td className="border px-4 py-2">
                                                <button
                                                    className="bg-blue-500 text-white px-3 py-1 rounded-md hover:bg-blue-600 transition"
                                                    onClick={() => handleSubmitBets(element)}
                                                >
                                                    Bets
                                                </button>
                                            </td>
                                        </tr>
                                    ))
                                ) : (
                                    <tr>
                                        <td colSpan="5" className="text-center p-4">
                                            No data available!!
                                        </td>
                                    </tr>
                                )}
                            </tbody>
                        </table>
                    </div>
                </div>


                {isBetpro && (
                    <div className=" fixed inset-0 bg-gray-800 bg-opacity-50 flex justify-center items-start pt-10">
                        <div className="animate-slideInFromBottom    rounded-lg shadow-lg max-w-[1200px] w-full">

                            <ShowBetsProfitLoss betHistoryData={betHistoryData} handleClose={() => SetBetpro(false)} />
                        </div>
                    </div>
                )}
            </div>
        </>
    )
}

export default ProfitAndLoss
