import React, { useState } from "react";
import { useExpenseList } from "../../hooks/useExpense";
import Avatar from "../common/Avatar";
import { useExpenseContext } from "../../pages/Expense/ExpensePage";
import { formatDate, formatUTCToLocalTime } from "../../utils/dateUtils";
import Pagination from "../common/Pagination";
import { ITEMS_PER_PAGE } from "../../utils/constants";

const ExpenseList = () => {
  const { setViewExpense } = useExpenseContext();
  const [currentPage, setCurrentPage] = useState(1);
  const pageSize = 10;

  const filter = {
    projectIds: [],
    statusIds: [],
    createdByIds: [],
    paidById: [],
    startDate: null,
    endDate: null,
  };

  const { data, isLoading, isError } = useExpenseList(ITEMS_PER_PAGE, currentPage, filter);
  if (isLoading) return <div>Loading...</div>;
  const items = data.data ?? [];
  const totalPages = data?.totalPages ?? 1;
  const hasMore = currentPage < totalPages;

  const paginate = (page) => {
    if (page >= 1 && page <= totalPages) {
      setCurrentPage(page);
    }
  };
  return (
    <div className="card ">
      <div className="card-datatable table-responsive">
        <div
          id="DataTables_Table_0_wrapper"
          className="dataTables_wrapper no-footer"
        >
          <table
            className="datatables-users table border-top dataTable no-footer dtr-column text-nowrap"
            id="DataTables_Table_0"
            aria-describedby="DataTables_Table_0_info"
            style={{ width: "100%" }}
          >
            <thead>
              <tr>
                <th
                  className="sorting sorting_desc"
                  tabIndex="0"
                  aria-controls="DataTables_Table_0"
                  rowSpan="1"
                  colSpan="2"
                  aria-label="Date: activate to sort column ascending"
                  aria-sort="descending"
                >
                  <div className="text-start ms-6">Date Time</div>
                </th>
                <th
                  className="sorting sorting_desc d-none d-sm-table-cell"
                  tabIndex="0"
                  aria-controls="DataTables_Table_0"
                  rowSpan="1"
                  colSpan="1"
                  aria-label="Expense Type: activate to sort column ascending"
                  aria-sort="descending"
                >
                  <div className="text-start ms-5">Expense Type</div>
                </th>
                <th
                  className="sorting sorting_desc d-none d-sm-table-cell"
                  tabIndex="0"
                  aria-controls="DataTables_Table_0"
                  rowSpan="1"
                  colSpan="1"
                  aria-label="Payment Mode: activate to sort column ascending"
                  aria-sort="descending"
                >
                  <div className="text-start ms-5">Payment Mode</div>
                </th>
                <th
                  className="sorting sorting_desc d-none d-sm-table-cell"
                  tabIndex="0"
                  aria-controls="DataTables_Table_0"
                  rowSpan="1"
                  colSpan="1"
                  aria-label="Paid By: activate to sort column ascending"
                  aria-sort="descending"
                >
                  <div className="text-start ms-5">Paid By</div>
                </th>
                <th
                  className="sorting d-none d-md-table-cell"
                  tabIndex="0"
                  aria-controls="DataTables_Table_0"
                  rowSpan="1"
                  colSpan="1"
                  aria-label="Amount: activate to sort column ascending"
                >
                  Amount
                </th>
                <th
                  className="sorting"
                  tabIndex="0"
                  aria-controls="DataTables_Table_0"
                  rowSpan="1"
                  colSpan="1"
                  aria-label="Status: activate to sort column ascending"
                >
                  Status
                </th>
                <th
                  className="sorting"
                  tabIndex="0"
                  aria-controls="DataTables_Table_0"
                  rowSpan="1"
                  colSpan="1"
                  aria-label="Status: activate to sort column ascending"
                >
                  Action
                </th>
              </tr>
            </thead>
            <tbody>
              {isLoading && (
                <tr>
                  <td colSpan={7} className="text-center py-3">
                    Loading...
                  </td>
                </tr>
              )}

              {!isLoading && items.length === 0 && (
                <tr>
                  <td colSpan={7} className="text-center py-3">
                    No expenses found.
                  </td>
                </tr>
              )}

              {!isLoading &&
                items.map((expense) => (
                  <tr key={expense.id} className="odd">
                    <td className="sorting_1" colSpan={2}>
                      <div className="d-flex justify-content-start align-items-center user-name ms-6">
                        <span>{formatUTCToLocalTime(expense.createdAt)}</span>
                      </div>
                    </td>
                    <td className="text-start d-none d-sm-table-cell ms-5">
                      {expense.expensesType?.name || "N/A"}
                    </td>
                    <td className="text-start d-none d-sm-table-cell ms-5">
                      {expense.paymentMode?.name || "N/A"}
                    </td>
                    <td className="text-start d-none d-sm-table-cell ms-5">
                      <div className="d-flex align-items-center">
                        <Avatar
                          size="xs"
                          classAvatar="m-0 "
                          firstName={expense.paidBy?.firstName}
                          lastName={expense.paidBy?.lastName}
                        />
                        <span>
                          {`${expense.paidBy?.firstName ?? ""} ${
                            expense.paidBy?.lastName ?? ""
                          }`.trim() || "N/A"}
                        </span>
                      </div>
                    </td>
                    <td className="d-none d-md-table-cell"><i className='bx bx-rupee b-xs'></i>{expense.amount}</td>
                    <td>
                      <span
                        style={{
                          backgroundColor: expense.status?.color || "#e2e3e5",
                          color: "#ffff",
                          padding: "2px 8px",
                          borderRadius: "0.375rem",
                          fontSize: "0.75rem",
                          fontWeight: 500,
                        }}
                      >
                        {expense.status?.name || "Unknown"}
                      </span>
                    </td>
                    <td>
                      <span
                        className="cursor-pointer"
                        onClick={() =>
                          setViewExpense({ expenseId: expense, view: true })
                        }
                      >
                        <i className="bx bx-show "></i>
                      </span>
                    </td>
                  </tr>
                ))}
            </tbody>
          </table>
        </div>
        {!isLoading && items.length > 0 && (
        <Pagination
          currentPage={currentPage}
          totalPages={totalPages}
          onPageChange={paginate}
        />
      )}
      </div>
  
    </div>
  );
};

export default ExpenseList;
