import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import moment from "moment";
import { accountStatement } from "../../redux/_reducers/_reducers";
import Loader from "../../component/Loader/Loader";

function AccountStatement() {
    const [fromDate, setFromDate] = useState(moment().subtract(7, 'days').unix());
    const [toDate, setToDate] = useState(moment().unix());
    const [selectedType, setSelectedType] = useState('Data');
    const [fetchedData, setFetchedData] = useState([]);
    const [statementData, setStatementData] = useState([]);
    const [page, setPage] = useState(100);
    const [currentPage, setCurrentPage] = useState(1);
    const itemsPerPage = 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(Number(event.target.value));
    };

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

    useEffect(() => {
        if (accountStatementData) {
            setStatementData(accountStatementData);
        }
    }, [accountStatementData]);

    const dispatch = useDispatch();

    const changeData = (fetchedData) => {
        if (fetchedData) {
            const updatedLedgerData = fetchedData.map((data, index) => {
                return {
                    Date: moment.unix(data.created_at).utcOffset("+05:30").format("DD-MM-YYYY"),
                    SrNo: index + 1,
                    Creditamount: parseFloat(data.amount > 0 ? data.amount : 0).toFixed(2).replace(/\.?0+$/, ''),
                    Debitamount: parseFloat(data.amount <= 0 ? data.amount : 0).toFixed(2).replace(/\.?0+$/, ''),
                    Description: data.description,
                    Balance: data.available_balance,
                };
            });
            setFetchedData(updatedLedgerData);
        }
    };

    const formatDate = (unixTimestamp) => {
        if (!unixTimestamp) return "";
        const date = new Date(unixTimestamp * 1000);
        return `${String(date.getMonth() + 1).padStart(2, '0')}/${String(date.getDate()).padStart(2, '0')}/${String(date.getFullYear()).slice(-2)}`;
    };

    const handleSubmit = async (e) => {
        if (e) e.preventDefault();
        if (fromDate && toDate) {
            const fetchData = async () => {
                try {
                    let reqData = {
                        "from_date": fromDate,
                        "to_date": toDate,
                        "limit": page,
                        "pageno": 1,
                    };
                    const response = await dispatch(accountStatement(reqData));
                    setFetchedData(response.payload);
                    changeData(response.payload?.data)
                } catch (err) {
                    console.error('Failed to fetch statement:', err);
                }
            };
            fetchData();
        }
    };

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

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

                <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">Account Statement</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>
                                <tr className="bg-[var(--light-header)] text-white">
                                    <th className="border px-4 py-2 text-center">Date</th>
                                    <th className="border px-4 py-2 text-center">Credit</th>
                                    <th className="border px-4 py-2 text-center">Debit</th>
                                    <th className="border px-4 py-2 text-center">Balance</th>
                                    <th className="border px-4 py-2 text-center">Remarks</th>
                                </tr>
                            </thead>
                            <tbody>
                                {statementData && statementData?.length > 0 ? (
                                    statementData?.map((element, i) => (
                                        <tr key={i} className="text-center">
                                            <td className="border px-4 py-2">
                                                {moment.unix(element?.created_at).format("DD MMM YYYY HH:mm A")}
                                            </td>
                                            <td className={`border px-4 py-2 ${element?.amount > 0 ? "text-green-600" : ""}`}>
                                                {element?.amount > 0 ? element?.amount : "-"}
                                            </td>
                                            <td className={`border px-4 py-2 ${element?.amount < 0 ? "text-red-600" : ""}`}>
                                                {element?.amount < 0 ? element?.amount : "-"}
                                            </td>
                                            <td className={`border px-4 py-2 ${element?.available_balance < 0 ? "text-red-600" : "text-green-600"}`}>
                                                {element?.available_balance}
                                            </td>
                                            <td className="border px-4 py-2">{element?.description}</td>
                                        </tr>
                                    ))
                                ) : (
                                    <tr>
                                        <td colSpan="5" className="border px-4 py-2 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 AccountStatement;
