import React from "react";
import VersionListSkeleton from "./VersionListSkeleton";
import { getDocuementsStatus } from "./Documents";
import Avatar from "../common/Avatar";
import { formatUTCToLocalTime } from "../../utils/dateUtils";
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import { DOWNLOAD_DOCUMENT, VERIFY_DOCUMENT } from "../../utils/constants";
import { FileIcon } from "../../utils/FileIcon";

const DocumentVersionList = ({
  versionLoding,
  versionList,
  isPending,
  setOpenDocument,
  VerifyDocument,
}) => {
  const canVerifyDocument = useHasUserPermission(VERIFY_DOCUMENT);
  const canDownloadDocument = useHasUserPermission(DOWNLOAD_DOCUMENT);
  const handleOpenDocument = () => {
    if (canDownloadDocument) {
      setOpenDocument(true);
    }
  };
  const contentTypeIcons = {
    "application/pdf": "fa-solid fa-file-pdf text-primary",
    "application/msword": "fa-solid fa-file-word text-primary",
    "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
      "fa-solid fa-file-word text-primary",
    "application/vnd.ms-excel": "fa-solid fa-file-excel text-success",
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
      "fa-solid fa-file-excel text-primary",
    "application/vnd.ms-powerpoint": "fa-solid fa-file-powerpoint text-primary",
    "application/vnd.openxmlformats-officedocument.presentationml.presentation":
      "fa-solid fa-file-powerpoint text-primary",
    "image/jpg": "fa-solid fa-file-image text-primary",
    "image/jpeg": "fa-solid fa-file-image text-primary",
    "image/png": "fa-solid fa-file-image text-primary",
    "image/gif": "fa-solid fa-file-image text-primary",
    "text/plain": "fa-solid fa-file-lines text-primary",
    "text/csv": "fa-solid fa-file-csv text-primary",
    "application/json": "fa-solid fa-file-code text-primary",
    default: "fa-solid fa-file text-primary",
  };

  const getIcon = (fileName = "") => {
    const ext = fileName.split(".").pop().toLowerCase();
    return contentTypeIcons[ext] || contentTypeIcons.default;
  };

  const sortedVersions = versionList?.data
    ? [...versionList.data].sort((a, b) => b.version - a.version)
    : [];

  if (versionLoding) {
    return <VersionListSkeleton items={2} />;
  }

  if (!sortedVersions.length) {
    return <p className="text-muted">No documents available.</p>;
  }

  const latestDoc = sortedVersions[0];

  return (
    <div className="accordion" id="docAccordion">
      <div className="accordion-item shadow-none">
        <h2 className="accordion-header" id="headingDoc">
          <button
            className="accordion-button"
            type="button"
            data-bs-toggle="collapse"
            data-bs-target="#collapseDoc"
            aria-expanded="true"
            aria-controls="collapseDoc"
          >
            <i className="bx bxs-folder me-2 text-warning fs-5"></i>
            {latestDoc.name} (Latest v{latestDoc.version})
          </button>
        </h2>
        <div
          id="collapseDoc"
          className="accordion-collapse collapse show"
          aria-labelledby="headingDoc"
          data-bs-parent="#docAccordion"
        >
          <div className="accordion-body p-2">
            <div className="list-group list-group-flush">
              {sortedVersions.map((document, index) => (
                <div
                  key={document.id}
                  className={`list-group-item list-group-item-action d-flex align-items-center cursor-pointer ${index > 0 ? "ms-4" : "" // indent only older versions
                    }`}
                >
                  <FileIcon
                    type={document.contentType}
                    size="fs-2"
                    className="me-2"
                  />

                  <div className="w-100">
                    <div className="d-flex justify-content-between align-items-center">
                      <small className=" fw-normal">{document.name}</small>
                      <small className=" fw-normal">
                        Version-{document.version}
                      </small>{" "}
                      <small className=" text-secondary fw-normal">
                        File Size: {document.fileSize} Kb
                      </small>
                    </div>
                    <div className="d-flex justify-content-between m-0">
                      <div
                        className="user-info text-start m-0"
                        onClick={handleOpenDocument}
                      >
                        <div className="d-flex align-items-center">
                          {formatUTCToLocalTime(document?.uploadedAt)} |
                          Uploaded by{" "}
                          <div className="d-flex align-items-center ms-1">
                            <Avatar
                              size="xs"
                              classAvatar="m-0"
                              firstName={document.uploadedBy?.firstName}
                              lastName={document.uploadedBy?.lastName}
                            />
                            <span className="text-truncate ms-1">
                              {`${document.uploadedBy?.firstName ?? ""} ${document.uploadedBy?.lastName ?? ""
                                }`.trim() || "N/A"}
                            </span>
                          </div>
                        </div>

                        <div className="d-flex align-items-center">
                          {document?.verifiedAt && (
                            <>
                              {formatUTCToLocalTime(document?.verifiedAt)} |{" "}
                              {document.isVerified
                                ? "Verified by "
                                : "Rejected by "}
                              <div className="d-flex align-items-center ms-1">
                                <Avatar
                                  size="xs"
                                  classAvatar="m-0"
                                  firstName={document.verifiedBy?.firstName}
                                  lastName={document.verifiedBy?.lastName}
                                />
                                <span className="text-truncate ms-1">
                                  {`${document.verifiedBy?.firstName ?? ""} ${document.verifiedBy?.lastName ?? ""
                                    }`.trim() || "N/A"}
                                </span>
                              </div>
                            </>
                          )}
                        </div>


                        {document?.updatedAt && (
                          <div className="d-flex align-items-center">
                            {formatUTCToLocalTime(document?.updatedAt)} |
                            Updated by{" "}
                            <div className="d-flex align-items-center ms-1">
                              <Avatar
                                size="xs"
                                classAvatar="m-0"
                                firstName={document.updatedBy?.firstName}
                                lastName={document.updatedBy?.lastName}
                              />
                              <span className="text-truncate ms-1">
                                {`${document.updatedBy?.firstName ?? ""} ${document.updatedBy?.lastName ?? ""
                                  }`.trim() || "N/A"}
                              </span>
                            </div>
                          </div>
                        )}
                      </div>

                      <div className="d-flex align-items-end">
                        {getDocuementsStatus(document.isVerified)}
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default DocumentVersionList;