import { useEffect, useState } from "react"
import { useDispatch, useSelector } from "react-redux";
import moment from "moment";
import { useLocation, useParams } from "react-router-dom";
import { myBetList } from "../../redux/_reducers/_reducers";
import Loader from "../../component/Loader/Loader";

function PendingBets() {
    const { type } = useParams();
    const dispatch = useDispatch();
    const [fromDate, setFromDate] = useState(moment().subtract(7, 'days').unix());
    const [toDate, setToDate] = useState(moment().unix());
    const [page, setPage] = useState(100);
    const [betHistoryData, setBetHistoryData] = useState([]);
    const [fetchedData, setFetchedData] = useState([]);
    const [sports, setSports] = useState(0);
    const [currentPage, setCurrentPage] = useState(0);
    const { myBetListData, loading } = useSelector(
        (state) => state.authentication
    );

    // const handleBetTypeChange = (e) => {
    //     setBetType(e.target.value);
    // };

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

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

    // const changeData = (fetchedData) => {
    //     if (fetchedData) {
    //         const updatedLedgerData = fetchedData.map((data, index) => {
    //             return {
    //                 Date: moment.unix(data.Placed).utcOffset("+05:30").format("DD-MM-YYYY"),
    //                 SrNo: index + 1,
    //                 Eventname: data.matchName,
    //                 Nation: data.SelectionName,
    //                 Result: data.winResult ? data.winResult : "Not Declered",
    //                 Side: data.Type,
    //                 Odds: data.Odds,
    //                 Stack: data.Stack,
    //                 PL: data.Liability,
    //                 BetStatus: data.Liability > 0 ? "Win" : "Loss",
    //                 IpAddress: data.ipAddress,
    //             };
    //         });
    //         setFetchedData(updatedLedgerData);
    //     }
    // };

    // const handleSaveDates = async (e) => {
    //     if (e) e.preventDefault();
    //     if (fromDate && toDate) {
    //         const fetchData = async () => {
    //             try {
    //                 let reqData =
    //                 {
    //                     "from_date": fromDate,
    //                     "to_date": toDate,
    //                     "limit": page,
    //                     "sport_id": sports,
    //                     "betType": "P",
    //                     "pageno": 1,
    //                     "market_id": "0",
    //                     "match_id": 0
    //                 }
    //                 const response = await dispatch(myBetList(reqData));
    //                 setFetchedData(response.payload?.data);
    //                 changeData(response.payload?.data)
    //             } catch (err) {
    //                 console.error('Failed to fetch statement:', err);
    //             }
    //         };
    //         fetchData();
    //     }
    // };

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

    // 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);
    //     }
    // };


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

    // const location = useLocation();
    // console.log(location, "ff");

    // const betType = location.state?.betType || "P";
    // const limit = 10;
    // const pageno = 1;


    useEffect(() => {
        let reqData =
        {
            "from_date": fromDate,
            "to_date": toDate,
            "limit": page,
            "sport_id": sports,
            "betType": "P",
            "pageno": 1,
            "market_id": "0",
            "match_id": 0
        }
        dispatch(myBetList(reqData));
    }, []);


    return (

        <>
            {loading && <Loader />}
            <div className="p-2">

                {/* <div className="bg-white px-2 py-4 rounded shadow-md">

                    <div className="grid grid-cols-2 gap-4">
                        <div>
                            <select className="w-full p-1 border rounded bg-white" value={betType} onChange={handleBetTypeChange}>
                                <option value="C">Complete (C)</option>
                                <option value="P">Pending (P)</option>
                            </select>
                        </div>
                        <div>
                            <select className="w-full p-1 border rounded bg-white" value={sports} onChange={handleSportsChange}>
                                <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>
                        </div>
                    </div>

                    <div className="grid sm:grid-cols-3 grid-cols-1 gap-4 mt-4">
                        <div>
                            <input className="w-full bg-white p-1 border rounded"
                                type="date"
                                id="fromDate"
                                value={moment.unix(fromDate).format("YYYY-MM-DD")}
                                onChange={(e) => handleDateChange(e, 'from')} />
                        </div>
                        <div>
                            <input className="w-full bg-white p-1 border rounded"
                                type="date"
                                id="toDate"
                                value={moment.unix(toDate).format("YYYY-MM-DD")}
                                onChange={(e) => handleDateChange(e, 'to')} />
                        </div>

                        <button
                            className="w-full bg-[var(--light-header)] text-white py-1.5 rounded hover:bg-[var(--secondary)] transition"
                            onClick={handleSaveDates}>
                            Search
                        </button>
                    </div>

                </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">Pending Bets</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 text-sm text-center">
                            <thead className="">
                                <tr className="bg-[var(--light-header)] text-white">
                                    <th className="p-2 whitespace-nowrap border">Sports Name</th>
                                    <th className="p-2 whitespace-nowrap border">Event Name</th>
                                    <th className="p-2 whitespace-nowrap border">Market Name</th>
                                    <th className="p-2 whitespace-nowrap border">Selection</th>
                                    <th className="p-2 whitespace-nowrap border">Type</th>
                                    <th className="p-2 whitespace-nowrap border">Odds Req.</th>
                                    <th className="p-2 whitespace-nowrap border">Stack</th>
                                    <th className="p-2 whitespace-nowrap border">Place Time</th>
                                </tr>
                            </thead>
                            <tbody>
                                {betHistoryData && betHistoryData?.length > 0 ? (
                                    betHistoryData?.map((element, i) => (
                                        <tr key={i} className={element.Type === "Back" ? "bg-[#8DD2F0]/60" : "bg-[#FCE3E4]"}>
                                            <td className="p-2 border text-center">{element?.sportName}</td>
                                            <td className="p-2 border whitespace-nowrap text-center">{element?.seriesName}</td>
                                            <td className="p-2 border whitespace-nowrap text-center">{element?.matchName}</td>
                                            <td className="p-2 border text-center">{element?.SelementctionName}</td>
                                            <td className="p-2 border text-center">{element?.Type}</td>
                                            <td className="p-2 border text-center">{element?.Odds}</td>
                                            <td className="p-2 border text-center">{element?.Stack}</td>
                                            <td className="p-2 border whitespace-nowrap text-center">{moment.unix(element?.Placed).format("DD-MM-YYYY HH:MM A")}</td>
                                        </tr>
                                    ))
                                ) : (
                                    <tr>
                                        <td colSpan="8" className="p-4 text-center">No data available!!</td>
                                    </tr>
                                )}
                            </tbody>
                        </table>
                    </div>

                </div>
            </div >

        </>
    )
}

export default PendingBets;