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

function DepositWithdrawHistory() {
    const dispatch = useDispatch();
    const [fromDate, setFromDate] = useState(moment().subtract(7, 'days').unix());
    const [toDate, setToDate] = useState(moment().unix());
    const [page, setPage] = useState('100');
    const [userChatListData, setUserChatListData] = useState([]);
    const [fetchedData, setFetchedData] = useState([]);
    const [betType, setBetType] = useState('AL');
    const [sports, setSports] = useState("AL");
    const [currentPage, setCurrentPage] = useState(0);

    const itemsPerPage = page;

    const { userchatlistData, loading } = useSelector(
        (state) => state.authentication
    );
    const handleBetTypeChange = (e) => {
        setBetType(e.target.value);
    };

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

    useEffect(() => {
        if (userchatlistData) {
            setUserChatListData(userchatlistData);
        }
    }, [userchatlistData]);

    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,
                        "page": 1,
                        "status": sports,
                        "type": betType
                    }
                    const response = await dispatch(userchatlist(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 formatDate = (unixTimestamp) => {
        const date = new Date(unixTimestamp * 1000);
        const options = {
            day: '2-digit',
            month: '2-digit',
            year: 'numeric',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: true,
        };
        return date.toLocaleString('en-GB', options);
    };


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


    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">
                        <select value={betType} onChange={handleBetTypeChange} className="border p-1 bg-white rounded">
                            <option value="Bet Type">Type</option>
                            <option value="D">Deposit</option>
                            <option value="W">Withdraw</option>
                        </select>
                        <select value={sports} onChange={handleSportsChange} className="border p-1 bg-white rounded">
                            <option value="AL">Status</option>
                            <option value="P">Pending</option>
                            <option value="C">Cancelled</option>
                            <option value="A">Approved</option>
                            <option value="D">Declined</option>
                        </select>
                    </div>
                    <div className="grid sm:grid-cols-3 grid-cols-1 gap-4 mt-4">
                        <input
                            type="date"
                            value={moment.unix(fromDate).format("YYYY-MM-DD")}
                            onChange={(e) => handleDateChange(e, 'from')}
                            className="border bg-white  p-1 rounded" />

                        <input type="date"
                            value={moment.unix(toDate).format("YYYY-MM-DD")}
                            onChange={(e) => handleDateChange(e, 'to')}
                            className="border bg-white  p-1 rounded" />

                        <button
                            onClick={handleSaveDates}
                            className="w-full bg-[var(--light-header)] text-white py-1.5 rounded hover:bg-[var(--secondary)] transition">
                            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">Bet History</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-[#96c6ef]">
                                    <th className="border whitespace-nowrap px-4 py-2">S No.</th>
                                    <th className="border whitespace-nowrap px-4 py-2">Account Detail</th>
                                    <th className="border whitespace-nowrap px-4 py-2">Payment</th>
                                    <th className="border whitespace-nowrap px-4 py-2">Status</th>
                                    <th className="border whitespace-nowrap px-4 py-2">Reason</th>
                                    <th className="border whitespace-nowrap px-4 py-2">Type</th>
                                    <th className="border whitespace-nowrap px-4 py-2">Amount</th>
                                    <th className="border whitespace-nowrap px-4 py-2">Date</th>
                                </tr>
                            </thead>
                            <tbody>
                                {userChatListData && userChatListData?.length > 0 ? (
                                    userChatListData?.map((element, i) => (
                                        <tr key={i} className="border">
                                            <td className="p-2">{i + 1}</td>
                                            <td className="p-2 whitespace-nowrap">
                                                {element?.accountHolder && <>Account Holder: {element.accountHolder} <br /></>}
                                                {element?.accountNumber && <>Account Number: {element?.accountNumber} <br /></>}
                                                {element?.ifscCode && <>IFSC: {element?.ifscCode}</>}
                                            </td>
                                            <td className="p-2">{element?.paymentMethod}</td>
                                            <td className="p-2">
                                                {element?.status === "P" ? "Pending" : element?.status === "A" ? "Approved" : element?.status === "C" ? "Cancelled" : element?.status === "D" ? "Declined" : "-"}
                                            </td>
                                            <td className="p-2">{element?.reason || "-"}</td>
                                            <td className="p-2">{element?.requestMethod === "D" ? "Deposit" : "Withdraw"}</td>
                                            <td className="p-2">{element?.amount}</td>
                                            <td className="p-2 whitespace-nowrap">{formatDate(element?.created_at)}</td>
                                        </tr>
                                    ))
                                ) : (
                                    <tr>
                                        <td colSpan="8" className="p-4 text-center">No data available!!</td>
                                    </tr>
                                )}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            {/* <div className="col-lg-3 score-tabbets " style={{ top: '100px' }}>
                <RightSidebar />
            </div> */}
        </>
    )
}

export default DepositWithdrawHistory