import React, { useState } from "react";
import { usePurchasesList } from "../../hooks/usePurchase";
import { ITEMS_PER_PAGE } from "../../utils/constants";
import Pagination from "../common/Pagination";
import { PurchaseColumn } from "./Purchasetable";
import { SpinnerLoader } from "../common/Loader";
import { useDebounce } from "../../utils/appUtils";
import { usePurchaseContext } from "../../pages/purchase/PurchasePage";

const PurchaseList = ({ searchString }) => {
  const { setViewPurchase, setManagePurchase, setChallan } =
    usePurchaseContext();
  const [currentPage, setCurrentPage] = useState(1);
  const debounceSearch = useDebounce(searchString, 300);
  const { data, isLoading } = usePurchasesList(
    ITEMS_PER_PAGE,
    currentPage,
    true,
    {},
    debounceSearch
  );

  const paginate = (page) => {
    if (page >= 1 && page <= (data?.totalPages ?? 1)) {
      setCurrentPage(page);
    }
  };

  const visibleColumns = PurchaseColumn.filter((col) => !col.hidden);

  return (
    <div className="card mt-2 page-min-h px-sm-4">
      <div className="table-responsive px-2">
        <table className="datatables-users table border-top text-nowrap">
          <thead>
            <tr>
              {visibleColumns.map((col) => (
                <th key={col.key} colSpan={col.colSpan || 1}>
                  <div className={col.className || ""}>{col.label}</div>
                </th>
              ))}
              <th>Action</th>
            </tr>
          </thead>

          <tbody>
            {/* LOADING */}
            {isLoading && (
              <tr>
                <td  colSpan={visibleColumns.length + 1} className="border-0">
                  <div className="py-6 py-12">
                    <SpinnerLoader />
                  </div>
                </td>
              </tr>
            )}
            {!isLoading && data?.data?.length === 0 && (
              <tr>
                <td
                  colSpan={visibleColumns.length}
                  className="text-center py-4 border-0"
                >
                  No Data Found
                </td>
              </tr>
            )}

            {!isLoading &&
              data?.data?.map((item, index) => (
                <tr key={item?.id || index}>
                  {visibleColumns.map((col) => (
                    <td key={col.key} className={col.className || ""}>
                      {col.render ? col.render(item) : item[col.key] || "NA"}
                    </td>
                  ))}
                  <td >
                    <div className="dropdown z-2">
                      <button
                        type="button"
                        className="btn btn-icon btn-text-secondary rounded-pill dropdown-toggle hide-arrow p-0"
                        data-bs-toggle="dropdown"
                        aria-expanded="false"
                      >
                        <i
                          className="bx bx-dots-vertical-rounded bx-sm text-muted"
                          data-bs-toggle="tooltip"
                          data-bs-offset="0,8"
                          data-bs-placement="top"
                          data-bs-custom-class="tooltip-dark"
                          title="More Action"
                        ></i>
                      </button>
                      <ul className="dropdown-menu dropdown-menu-end">
                        <li>
                          <a
                            className="dropdown-item cursor-pointer"
                            onClick={() =>
                              setViewPurchase({
                                isOpen: true,
                                purchaseId: item.id,
                              })
                            }
                          >
                            <i className="bx bx-show me-2"></i>
                            <span className="align-left">view</span>
                          </a>
                        </li>
                        <li>
                          <a
                            className="dropdown-item cursor-pointer"
                            onClick={() =>
                              setManagePurchase({
                                isOpen: true,
                                purchaseId: item.id,
                              })
                            }
                          >
                            <i className="bx bx-edit me-2"></i>
                            <span className="align-left">Edit</span>
                          </a>
                        </li>
                        <li>
                          <a
                            className="dropdown-item cursor-pointer"
                            onClick={() =>
                              setChallan({
                                isOpen: true,
                                purchaseId: item.id,
                              })
                            }
                          >
                            <i className="bx bx-file bx-plus me-2"></i>

                            <span className="align-left">Add Delivery Challan</span>
                          </a>
                        </li>
                      </ul>
                    </div>
                  </td>
                </tr>
              ))}
          </tbody>
        </table>
      </div>

      {data?.data?.length > 0 && (
        <Pagination
          currentPage={currentPage}
          totalPages={data.totalPages}
          onPageChange={paginate}
        />
      )}
    </div>
  );
};

export default PurchaseList;
