import React, { useState } from "react";
import { useCollections } from "../../hooks/useCollections";
import { ITEMS_PER_PAGE } from "../../utils/constants";
import { formatFigure, localToUtc, useDebounce } from "../../utils/appUtils";
import { formatUTCToLocalTime } from "../../utils/dateUtils";
import Pagination from "../common/Pagination";

const CollectionList = ({ fromDate, toDate, isPending, searchString }) => {
  const [currentPage, setCurrentPage] = useState(1);
  const searchDebounce = useDebounce(searchString, 500);

  const { data, isLoading, isError, error } = useCollections(
    ITEMS_PER_PAGE,
    currentPage,
    localToUtc(fromDate),
    localToUtc(toDate),
    isPending,
    true,
    searchDebounce
  );

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

  const collectionColumns = [
    {
      key: "invoiceDate",
      label: "Invoice Date",
      getValue: (col) => (
        <span
          className="text-truncate d-inline-block"
          style={{ maxWidth: "200px" }}
        >
          {formatUTCToLocalTime(col.invoiceDate)}
        </span>
      ),
      align: "text-start",
    },
    {
      key: "invoiceId",
      label: "Invoice Id",
      getValue: (col) => (
        <span
          className="text-truncate d-inline-block"
          style={{ maxWidth: "200px" }}
        >
          {col?.invoiceNumber ?? "-"}
        </span>
      ),
      align: "text-start",
    },
    {
      key: "project",
      label: "Project",
      getValue: (col) => (
        <span
          className="text-truncate d-inline-block"
          style={{ maxWidth: "200px" }}
        >
          {col?.project?.name ?? "-"}
        </span>
      ),
      align: "text-start",
    },
    {
      key: "submittedDate",
      label: "Submitted Date",
      getValue: (col) => (
        <span
          className="text-truncate d-inline-block"
          style={{ maxWidth: "200px" }}
        >
          {formatUTCToLocalTime(col.createdAt)}
        </span>
      ),
      align: "text-start",
    },
    {
      key: "expectedSubmittedDate",
      label: "Expected Payment Date",
      getValue: (col) => (
        <span
          className="text-truncate d-inline-block"
          style={{ maxWidth: "200px" }}
        >
          {formatUTCToLocalTime(col.exceptedPaymentDate) ?? "-"}
        </span>
      ),
      align: "text-start",
    },
    {
      key: "amount",
      label: "Amount",
      getValue: (col) => (
        <span
          className="text-truncate d-inline-block"
          style={{ maxWidth: "200px" }}
        >
          {formatFigure(col?.basicAmount, { type: "currency", currency: "INR" }) ?? 0}
        </span>
      ),
      align: "text-end",
    },
    {
      key: "balance",
      label: "Balance",
      getValue: (col) => (
        <span
          className="text-truncate d-inline-block py-3"
          style={{ maxWidth: "200px" }}
        >
          {formatFigure(col?.balanceAmount, { type: "currency", currency: "INR" }) ?? 0}
        </span>
      ),
      align: "text-end",
    },
  ];

  if (isLoading) return <p>Loading...</p>;
  if (isError) return <p>{error.message}</p>;

  return (
    <div className="card ">
      <div
        className="card-datatable table-responsive page-min-h"
        id="horizontal-example"
      >
        <div className="dataTables_wrapper no-footer mx-5 pb-2">
          <table className="table dataTable text-nowrap">
            <thead>
              <tr className="table_header_border">
                {collectionColumns.map((col) => (
                  <th key={col.key} className={col.align}>
                    {col.label}
                  </th>
                ))}
                <th className="sticky-action-column bg-white text-center">
                  Action
                </th>
              </tr>
            </thead>
            <tbody>
              {Array.isArray(data?.data) && data.data.length > 0 ? (
                data.data.map((row, i) => (
                  <tr key={i}>
                    {collectionColumns.map((col) => (
                      <td key={col.key} className={col.align}>
                        {col.getValue(row)}
                      </td>
                    ))}
                    <td
                      className="sticky-action-column text-center"
                      style={{ padding: "12px 8px" }}
                    >
                      <div className="d-flex justify-content-center gap-2">
                        <i className="bx bx-show text-primary cursor-pointer"></i>
                        <i className="bx bx-edit text-secondary cursor-pointer"></i>
                        <i className="bx bx-trash text-danger cursor-pointer"></i>
                      </div>
                    </td>
                  </tr>
                ))
              ) : (
                <tr style={{ height: "200px" }}>
                  <td
                    colSpan={collectionColumns.length + 1}
                    className="text-center border-0 align-middle"
                  >
                    No Collections Found
                  </td>
                </tr>
              )}
            </tbody>
          </table>
          {data?.data?.length > 0 && (
            <div className="d-flex justify-content-start mt-2">
              <Pagination
                currentPage={currentPage}
                totalPages={data?.totalPages}
                onPageChange={paginate}
              />
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default CollectionList;
