import { useContext, useEffect, useState, useRef } from "react";
import { useNavigate } from "react-router-dom";
import { AppContext } from "../../Hooks/useContext/appContext";
import SelectDropdown from "../../pageElements/SelectDropdown";
import { DocCard } from "../../pageElements/Cards";
import { db } from "../../firebase";
import Toggle from "../../pageElements/Toggle.js";
import MobileContent from "../MobileContent";
import {
  collection,
  deleteDoc,
  doc,
  documentId,
  onSnapshot,
  query,
  where,
} from "firebase/firestore";
import ListPagination from "../../pageElements/ListPagination";
import ConfirmModal from "../Modals/ConfirmModal";
import "../../styles/doclist-page.scss";

const DocumentListPage = ({ perPage }) => {
  const size = window.innerWidth < 440;
  const [isMobile, setIsMobile] = useState(size);
  const count = useRef(null);
  const navigate = useNavigate();
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [selectedDocumentId, setSelectedDocumentId] = useState(null);
  const [allDocs, setAllDocs] = useState(null);
  const { appState } = useContext(AppContext);
  const [totalPages, setTotalPages] = useState(1);
  const { group } = appState;
  const [page, setPage] = useState(1);
  const [order, setOrder] = useState("parentCaseName");
  const appUserId = group ? group.appUserId : null;
  const [isBusy, setIsBusy] = useState(false);
  const [selectedDocumentType, setSelectedDocumentType] = useState();
  const [showModal, setShowModal] = useState(false);

  const apiUrl =
    process.env.NODE_ENV === "development"
      ? process.env.REACT_APP_API_DEV
      : process.env.REACT_APP_API_PROD;

  useEffect(() => {
    if (count.current == null) {
      setIsMobile(window.innerWidth < 440);
    }
    if (count.current < 3) {
      setIsMobile(window.innerWidth < 440);
    }
    return () => {
      const temp = (count.current = count.current + 1);
      count.current = temp;
    };
  }, []);

  function getDocuments() {
    if (!appUserId) {
      setAllDocs([]);
      return;
    }
    const q = query(
      collection(db, "documents"),
      where("ownerId", "==", appUserId)
    );
    const unsub = onSnapshot(q, (snapshot) => {
      const data = snapshot.docs.map((doc) => ({
        ...doc.data(),
        documentId: doc.id,
      }));
      if (order === "parentCaseName") {
        data.sort((a, b) => {
          return a.parentCaseName.toLowerCase() > b.parentCaseName.toLowerCase()
            ? 1
            : -1;
        });
      } else if (order === "parentCaseName2") {
        data.sort((a, b) => {
          return a.parentCaseName.toLowerCase() < b.parentCaseName.toLowerCase()
            ? 1
            : -1;
        });
      }
      const pages = Math.ceil(data.length / perPage);
      if (page > pages) {
        setPage(pages);
      }
      setTotalPages(pages);
      setAllDocs(data);
    });
    return unsub;
  }

  useEffect(getDocuments, [appUserId, order]);

  async function deleteFromDb(documentId) {
    if (isBusy) {
      return;
    }

    setIsBusy(true);
    try {
      const docRef = doc(db, "documents", `${documentId}`);
      await deleteDoc(docRef);
      setShowDeleteModal(false);
    } catch (err) {
      console.log("Error deleting document from db:", err);
    }
    setIsBusy(false);
  }

  const handleNovos = (e) => {
    navigate("/how-to");
  };

  async function deleteFromStorage() {
    const selectedDoc = allDocs.filter((doc) => {
      return doc.documentId == selectedDocumentId;
    });

    const respGens = selectedDoc[0].responseGenerations;

    try {
      const response = await fetch(
        `${apiUrl}/deleteDoc/${selectedDocumentId}/${selectedDocumentType}/${respGens}`,
        {
          method: "POST",
        }
      );
      const res = response;
      return res;
    } catch (error) {
      console.error("Error deleting document from storage:", error);
    }
  }

  const dropDownOptions = [
    { label: "Associated case name a - z", value: "parentCaseName" },
    { label: "Associated case name z - a", value: "parentCaseName2" },
  ];

  function handleNavigate(
    documentId,
    caseId,
    documentType,
    clientPosition,
    responseGenerations
  ) {
    const docId = String(documentId);
    const docType = String(documentType);
    if (documentType === "interrogatories-out") {
      //may include other in future ie req for admission
      navigate(`/reqedit/${docId}/interrogatories-out/${caseId}`);
    } else {
      navigate(
        `/docedit/${docId}/${caseId}/${docType}/${clientPosition}/${responseGenerations}`
      );
    }
  }

  function handleCancelDelete() {
    if (!isBusy) {
      setShowDeleteModal(false);
    }
  }

  function handleDeleteDocument() {
    deleteFromDb(selectedDocumentId);
    deleteFromStorage(selectedDocumentId, selectedDocumentType);
  }

  function confirmDelete(documentId, docType) {
    setSelectedDocumentId(documentId);
    setSelectedDocumentType(docType);
    setShowDeleteModal(true);
  }

  if (!group) {
    return null;
  }

  const DesktopContent = () => {
    return (
      <>
        <div className="doc-list-header">
          <h2 className="doc-header-text">Documents</h2>
          <div className="user-name-container">{group.firm}</div>
        </div>
        {allDocs === null ? <div>Loading...</div> : null}
        {allDocs !== null ? (
          <div className="content-container">
            {allDocs.length > 0 ? (
              <div className="document-list-upper-wrapper">
                <div className="list-upper-left"></div>
                <div className="list-upper-right">
                  <div className="d-flex justify-content-end mb-3">
                    <SelectDropdown
                      dropDownOptions={dropDownOptions}
                      titleText="Sort documents"
                      handleSelect={setOrder}
                    />
                  </div>
                </div>
              </div>
            ) : (
              <></>
            )}
            <div className="document-list-lower-wrapper">
              {allDocs.length > 0 ? (
                allDocs
                  .slice((page - 1) * perPage, page * perPage)
                  .map((doc, i) => (
                    <DocCard
                      key={`doccard-${i}`}
                      title={doc.docTitle}
                      parentCaseNumber={doc.parentCaseNumber}
                      parentCaseName={doc.parentCaseName}
                      parentCaseId={doc.parentCaseId}
                      createdAt={doc.createdAt}
                      docType={doc.docType}
                      documentId={doc.documentId}
                      dateServed={doc.dateServed}
                      confirmDelete={confirmDelete}
                      handleNavigate={handleNavigate}
                      displayDeleteButton={true}
                      responseGenerations={doc.responseGenerations}
                      clientPosition={doc.clientPosition}
                    />
                  ))
              ) : (
                <div className="nodocs-text-container">
                  <p className="nodocs-text">
                    {" "}
                    You have not uploaded any documents yet.
                  </p>
                  <p className="nodocs-light-text">To upload a document:</p>
                  <ol>
                    <li className="nodocs-list-item">
                      Navigate to the cases view (above link in navigation bar).{" "}
                    </li>
                    <li>
                      {" "}
                      Click "View Case" to select the case with which your
                      document will be associated. This will open the Case
                      Detail view.{" "}
                    </li>
                    <li className="nodocs-list-item">
                      Note: If you have not yet created any cases, you will need
                      to create one first - click "Create Case" and follow the
                      prompts.
                    </li>
                    <li className="nodocs-list-item">
                      In the case detail view, click "Upload Case Document" and
                      select a document from your computer for upload.
                    </li>
                    <li className="nodocs-list-item">
                      Your document will be parsed into a processable form. You
                      will then be able to generate a response to the document.
                    </li>
                  </ol>
                </div>
              )}
            </div>
            {totalPages > 1 ? (
              <div className="mb-3">
                <ListPagination
                  page={page}
                  totalPages={totalPages}
                  setPage={setPage}
                />
              </div>
            ) : null}
          </div>
        ) : null}
        {showDeleteModal && selectedDocumentId !== null ? (
          <ConfirmModal
            onCancel={handleCancelDelete}
            onConfirm={handleDeleteDocument}
            buttonLabelText="Delete"
            modalText="Confirm that you want to permanently delete this document."
          />
        ) : null}
      </>
    );
  };
  return isMobile ? <MobileContent /> : <DesktopContent />;
};

export default DocumentListPage;

/*

  const [verbValue, setVerbValue] = useState(1);
  const handleToggle = (val) => setVerbValue(val);

  <div className="toggle-outer">
        <div className="toggle-header">
          {" "}
          <p
            onClick={handleNovos}
            href=""
            className="doclist-toggle-link"
          >
            Novos
          </p>
        </div>
        <div className="toggle-box">
          <p className="select-billing-text">Min</p>
          <Toggle value={verbValue} onClick={handleToggle} />
          <p className="select-billing-text">Max</p>
        </div>
    </div>
*/
