import React, { useState } from "react";
import {
  useDeletePurchaseInvoice,
  usePurchasesList,
} from "../../hooks/usePurchase";
import {
  ADD_DELIVERY_CHALLAN,
  DELETEPURCHASE_INVOICE,
  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";
import ConfirmModal from "../common/ConfirmModal";
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import { DropdownItem, getPurchaseActions } from "./PurchaseActions";

const PurchaseList = ({ searchString, isActive }) => {
  const { setViewPurchase, setManagePurchase, setChallan, setAddPayment } =
    usePurchaseContext();
  const [currentPage, setCurrentPage] = useState(1);
  const { mutate: DeletePurchaseInvoice, isPending } =
    useDeletePurchaseInvoice();
  const [IsDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [deletingId, setDeletingId] = useState(null);

  const canAddChallan = useHasUserPermission(ADD_DELIVERY_CHALLAN);
  const canDelete = useHasUserPermission(DELETEPURCHASE_INVOICE);

  const debounceSearch = useDebounce(searchString, 300);
  const { data, isLoading } = usePurchasesList(
    ITEMS_PER_PAGE,
    currentPage,
    // true,
    !isActive,
    {},
    debounceSearch
  );

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

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

  const handleDeleteRestore = (id) => {
    DeletePurchaseInvoice(
      { id, isActive: isActive }, // delete if active, restore if deleted
      {
        onSettled: () => {
          setDeletingId(null);
          setIsDeleteModalOpen(false);
        },
      }
    );
  };

  return (
    <>
      {IsDeleteModalOpen && (
        <ConfirmModal
          isOpen={IsDeleteModalOpen}
          type={!isActive ? "delete" : "undo"}
          header={!isActive ? "Delete Invoice" : "Restore Invoice"}
          message={
            !isActive
              ? "Are you sure you want to delete?"
              : "Are you sure you want to restore?"
          }
          onSubmit={handleDeleteRestore}
          onClose={() => setIsDeleteModalOpen(false)}
          loading={isPending}
          paramData={deletingId}
        />
      )}
      <div className="card mt-2 page-min-h table-responsive  px-sm-4">
        <div className="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"
                    style={{ height: "300px", verticalAlign: "middle" }}
                  >
                    <div className="d-flex justify-content-center align-items-center w-100 h-100">
                      <SpinnerLoader />
                    </div>
                  </td>
                </tr>
              )}

              {!isLoading && data?.data?.length === 0 && (
                <tr>
                  <td
                    colSpan={visibleColumns.length + 1}
                    className="text-center border-0"
                    style={{ height: "400px", verticalAlign: "middle" }}
                  >
                    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} cursor-pointer` || ""}
                        onClick={() =>
                          setViewPurchase({
                            isOpen: true,
                            purchaseId: item.id,
                          })
                        }
                      >
                        {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">
                          {getPurchaseActions({
                            item,
                            isActive,
                            canDelete,
                            canAddChallan,
                            setViewPurchase,
                            setManagePurchase,
                            setDeletingId,
                            setIsDeleteModalOpen,
                            setChallan,
                            setAddPayment,
                          }).map((action) => (
                            <DropdownItem
                              key={action.key}
                              icon={action.icon}
                              label={action.label}
                              onClick={action.onClick}
                            />
                          ))}
                        </ul>
                      </div>
                    </td>
                  </tr>
                ))}
            </tbody>
          </table>
        </div>

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

export default PurchaseList;
