import React from "react";
import { useDeliverChallane } from "../../hooks/usePurchase";
import { SpinnerLoader } from "../common/Loader";
import { formatUTCToLocalTime } from "../../utils/dateUtils";
import { FileView } from "../Expenses/Filelist";

const DeliverChallanList = ({ purchaseId }) => {
  const { data, isLoading, isError, error } = useDeliverChallane(purchaseId);
  if (isLoading) {
    return (
  <div className="d-flex justify-content-center align-items-center text-center vh-50">
        <SpinnerLoader />
      </div>
    );
  }

  if (isError) {
    return (
      <div className="py-3">
        <Error error={error} />
      </div>
    );
  }
  if (!isLoading && data.length === 0)
    return (
      <div className="d-flex justify-content-center align-items-center text-center vh-50">
        <p className="mb-0">Not Yet</p>
      </div>
    );

  return (
    <div className="list-group list-group-flush text-start">
      {data.map((item) => (
        <div
          key={item.id}
          className="list-group-item d-flex justify-content-between align-items-start flex-wrap px-3 w-full"
        >
          {/* LEFT SIDE */}
          <div className=" pe-3 text-break w-full">
            <div className="d-flex justify-content-between">
              <p className="mb-1 fw-semibold">{item.deliveryChallanNumber}</p>
              <small className="text-muted text-end">
                {formatUTCToLocalTime(item.deliveryChallanDate, true)}
              </small>
            </div>

            <div className="mb-1 small text-muted text-break">
              <span className="fw-semibold me-1">Invoice:</span>
              {item.purchaseInvoice?.title} (
              {item.purchaseInvoice?.purchaseInvoiceUId})
            </div>

            <p className="mb-1 text-break">
              <span className="fw-semibold">Description:</span>{" "}
              {item.description || "-"}
            </p>

            {item.attachment?.preSignedUrl && (
              <FileView file={item.attachment} />
            )}
          </div>
        </div>
      ))}
    </div>
  );
};

export default DeliverChallanList;
