import React, { useState } from "react";
import {
  useDocumentDetails,
  useDocumentVersionList,
  useVerifyDocument,
} from "../../hooks/useDocument";
import { getDocuementsStatus, useDocumentContext } from "./Documents";
import { formatUTCToLocalTime } from "../../utils/dateUtils";
import Avatar from "../common/Avatar";
import {
  DOWNLOAD_DOCUMENT,
  ITEMS_PER_PAGE,
  VERIFY_DOCUMENT,
} from "../../utils/constants";
import DocumentDetailsSkeleton from "./DocumentDetailsSkeleton ";
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import DocumentVersionList from "./DocumentVersionList";

const ViewDocument = () => {
  const { viewDoc, setOpenDocument } = useDocumentContext();
  const [currentPage, setCurrentPage] = useState(1);
  const [showVersions, setShowVersions] = useState(false);
  const canVerifyDocument = useHasUserPermission(VERIFY_DOCUMENT);

  // Document Details
  const { data, isLoading, isError, error } = useDocumentDetails(
    viewDoc?.document
  );

  // Document Versions (fetch only if toggle is ON)
  const {
    data: versionList,
    isLoading: versionLoading,
  } = useDocumentVersionList(
    showVersions ? data?.parentAttachmentId : null,
    ITEMS_PER_PAGE - 10,
    currentPage
  );

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

  // Verify / Reject
  const { mutate: VerifyDoc, isPending } = useVerifyDocument();
  const VerifyDocument = () => {
    VerifyDoc({ documentId: viewDoc?.document, isVerify: true });
  };
  const RejectDocument = () => {
    VerifyDoc({ documentId: viewDoc?.document, isVerify: false });
  };

  if (isLoading) return <DocumentDetailsSkeleton />;
  if (isError)
    return (
      <div>
        <p>{error?.response?.data?.message || error?.message}</p>
        <p className="danger-text">{error?.response?.status}</p>
      </div>
    );

  return (
    <div className="p-3">
      <p className="fw-bold fs-5 mb-3 border-bottom pb-2">Document Details</p>

      {/* Document Info Rows */}
      <div className="row mb-2 text-start">
        <div className="col-12 col-md-6 d-flex">
          <span className="fw-semibold me-2" style={{ minWidth: "140px" }}>
            Category:
          </span>
          <span className="text-muted">
            {data.documentType?.documentCategory?.name || "-"}
          </span>
        </div>
        <div className="col-12 col-md-6 d-flex">
          <span className="fw-semibold me-2" style={{ minWidth: "140px" }}>
            Type:
          </span>
          <span className="text-muted">{data.documentType?.name || "-"}</span>
        </div>
      </div>

      <div className="row mb-2 text-start">
        <div className="col-12 col-md-6 d-flex">
          <span className="fw-semibold me-2" style={{ minWidth: "140px" }}>
            Document Name:
          </span>
          <span className="text-muted">{data.name || "-"}</span>
        </div>
        <div className="col-12 col-md-6 d-flex">
          <span className="fw-semibold me-2" style={{ minWidth: "140px" }}>
            Document ID:
          </span>
          <span className="text-muted">{data.documentId || "-"}</span>
        </div>
      </div>

      <div className="row mb-2 text-start">
        <div className="col-12 col-md-6 d-flex">
          <span className="fw-semibold me-2" style={{ minWidth: "140px" }}>
            Uploaded At:
          </span>
          <span className="text-muted">
            {formatUTCToLocalTime(data.uploadedAt)}
          </span>
        </div>
        
      </div>

      <div className="row mb-2 text-start">
        <div className="col-12 d-flex">
          <span className="fw-semibold me-2" style={{ minWidth: "140px" }}>
            Tags:
          </span>
          <div className="d-flex flex-wrap gap-2">
            {data.tags?.length > 0 ? (
              data.tags.map((t, i) => (
                <span
                  key={i}
                  className="badge rounded-pill bg-label-secondary"
                >
                  {t.name}
                </span>
              ))
            ) : (
              <span className="text-muted">-</span>
            )}
          </div>
        </div>
      </div>

      <div className="row mb-3 text-start">
        <div className="col-12 d-flex">
          <span className="fw-semibold me-2" style={{ minWidth: "140px" }}>
            Description:
          </span>
          <span className="text-muted">{data.description || "-"}</span>
        </div>
      </div>

      {/* Toggle for Versions */}
      <div className="d-flex justify-content-between align-items-center mb-3">
        <p className="m-0 fw-semibold fs-6">Documents:</p>
        <div className="form-check form-switch">
          <label className="form-check-label" htmlFor="showVersionsSwitch">
            Show Versions
          </label>
          <input
            className="form-check-input"
            type="checkbox"
            id="showVersionsSwitch"
            checked={showVersions}
            onChange={(e) => setShowVersions(e.target.checked)}
          />
        </div>
      </div>

      <DocumentVersionList
        versionLoding={versionLoading}
        versionList={versionList}
        isPending={isPending}
        setOpenDocument={setOpenDocument}
        VerifyDocument={VerifyDocument}
        RejectDocument={RejectDocument}
        showVersions={showVersions}
        latestDoc={data}
      />
    </div>
  );
};

export default ViewDocument;