import React, { useEffect, useContext, useState } from "react";
import { useNavigate, Link } from "react-router-dom";
import { DetailCard } from "../../pageElements/DetailCard.js";
import Button from "../../pageElements/Button";
import CreateModal from "../Modals/CreateModal.js";
import UploadModal from "../Modals/UploadModal.js";
import ConfirmModal from "../Modals/ConfirmModal.js";
import { db } from "../../firebase";
import { useParams } from "react-router-dom";
import { AppContext } from "../../Hooks/useContext/appContext.js";
import LoadingSpinner from "../../pageElements/LoadingSpinner";
import { ArrowLeft } from "react-bootstrap-icons";
import {
  doc,
  getDoc,
  updateDoc,
  onSnapshot,
  increment,
} from "firebase/firestore";

const CaseDetailsPage = () => {
  const { caseId } = useParams();
  const [subCase, setSubCase] = useState(null);
  const navigate = useNavigate();
  const [showUploadModal, setShowUploadModal] = useState();
  const [uploadType, setUploadType] = useState();
  const [showCreateModal, setShowCreateModal] = useState();
  const [showConfirmModal, setShowConfirmModal] = useState();
  const [isLoading, setIsLoading] = useState(false);
  const [docsAllowed, setDocsAllowed] = useState(null);
  const [docsGenerated, setDocsGenerated] = useState(null);
  const [document, setDocument] = useState(null);
  const { appState } = useContext(AppContext);
  const { group } = appState;
  const appUserId = group ? group.appUserId : null;
  const fbUserId = group ? group.fbAuthUid : null;
  const message =
    "Parsing document.  Please be patient, this may take several minutes.";
  const apiUrl =
    process.env.NODE_ENV === "development"
      ? process.env.REACT_APP_API_DEV
      : process.env.REACT_APP_API_PROD;

  function getDocument(docId, caseId) {
    const docRef = doc(db, "documents", `${docId}`);
    const res = getDoc(docRef).then(function (doc) {
      if (doc.exists) {
        const data = doc.data();
        if (data.docType != undefined) {
          const caseId = data.parentCaseId;
          const docType = data.docType;
          const clientPosition = data.clientPosition;
          if (docType != "combined-numbered") {
            const responseGenerations = 1;
            navigate(
              `/docedit/${docId}/${caseId}/${docType}/${clientPosition}/${responseGenerations}`
            );
          } else if (docType == "combined-numbered") {
            const responseGenerations = 0;
            navigate(
              `/docedit/${docId}/${caseId}/${docType}/${clientPosition}/${responseGenerations}`
            );
          }
        } else {
          setTimeout(getDocument, 30000, docId, caseId);
        }
      } else {
        console.log("No such document.");
      }
    });
  }

  function handleIncomingDiscoveryRequest(docId, isComplaint, clientPosition) {
    //ONLY TRIGGER FROM THIS SIDE IF IT IS COMBINED NUMBERED
    setTimeout(generateRespIncomingDiscReq, 10000, docId, clientPosition);
    setTimeout(getDocument, 50000, docId);
  }
  // isComplaint = true - NEVER CHANGE THIS/THESE ARGS
  async function generateOutgoingDiscReq(docId, clientPosition) {
    try {
      const response = await fetch(
        `${apiUrl}/v1/generate-outgoing-disc-req/${docId}/${clientPosition}`,
        {
          method: "POST",
        }
      );
      const res = response;
      return res;
    } catch (err) {
      console.log("generateOutgoingDiscReq out error", err);
    }
  }
  //  isComplaint = false - NEVER CHANGE THESE ARGS
  async function generateRespIncomingDiscReq(docId, clientPosition) {
    console.log(
      "generateRespIncomingDiscReq ------------------------fired----------------->"
    );
    try {
      const response = await fetch(
        `${apiUrl}/v1/generate-disc-responses/${docId}/${clientPosition}`,
        {
          method: "POST",
        }
      );
      const res = response;
      return res;
    } catch (err) {
      console.log("generateRespIncomingDiscReq resp err", err);
    }
  }

  async function handleSuccess(docId, docType, radioValue) {
    setShowUploadModal(false);
    const clientPosition = subCase.clientPosition;

    if (docType === "complaint") {
      const isComplaint = true;
      generateOutgoingDiscReq(docId, isComplaint, clientPosition);
      setTimeout(handleNavEdit, 60000, docId, caseId);
    } else {
      const isComplaint = false;
      handleIncomingDiscoveryRequest(docId, isComplaint, clientPosition);
    }
  }

  function getCase() {
    const docRef = doc(db, "cases", caseId);
    const unsub = onSnapshot(docRef, (snapshot) => {
      if (snapshot.exists() && snapshot.data().ownerId === appUserId) {
        setSubCase({ ...snapshot.data(), id: snapshot.id });
      } else {
        setSubCase(null);
      }
    });
    return unsub;
  }

  useEffect(getCase, [caseId, appUserId]);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const docRef = doc(db, "users", fbUserId);
        const response = await getDoc(docRef).then(function (doc) {
          if (doc.exists) {
            const data = doc.data();
            setDocsAllowed(data.docsAllowedPerMonth);
            setDocsGenerated(data.docsGenerated);
            return data;
          } else {
            console.log("No such document.");
          }
        });
      } catch (err) {
        console.error(err);
      }
    };
    fetchData();
  }, [fbUserId]);

  const handleNavigate = (docId, caseId) => {
    getDocument(docId, caseId);
  };

  const handleNavEdit = (documentId, caseId) => {
    if (!documentId || !caseId) {
      return;
    }
    navigate(`/reqedit/${documentId}/interrogatories-out/${caseId}`);
  };

  const handleUploadDoc = () => {
    if (docsAllowed - docsGenerated > 0) {
      setUploadType("discovery");
      setShowUploadModal(true);
    } else {
      setShowConfirmModal(true);
    }
  };

  const handleUploadComplaint = () => {
    if (docsAllowed - docsGenerated > 0) {
      setUploadType("complaint");
      setShowUploadModal(true);
    } else {
      setShowConfirmModal(true);
    }
  };

  const handleConfirmDocType = (docType) => {
    setShowConfirmModal(true);
  };

  const handleCancelConfirm = () => {
    setShowConfirmModal(false);
  };

  const handleConfirmUpgrade = () => {
    const isUpgrade = true;
    const currentPlan = group?.subscriptionPlan;
    navigate(`/signup/${isUpgrade}/${currentPlan}`);
  };

  const ButtonContent = () => {
    return (
      <div className="details-button-container">
        <div className="details-butn-wrapper">
          <div className="details-butn-sub-wrapper-r">
            <Link className="view-all-link" to="/cases">
              <span className="arrow-wrapper">
                <ArrowLeft size="20px" />
              </span>
              <span className="details-back-wrapper">Back</span>
            </Link>
          </div>
          <div className="details-butn-sub-wrapper-l">
            <Button
              onClick={() => setShowCreateModal(true)}
              labelText="Edit Case Details"
              className="primary-button"
            />
          </div>
        </div>
        <div className="details-complaint-button-box">
          <Button
            className="secondary-button back-button"
            onClick={handleUploadComplaint}
            labelText="Upload Complaint"
          />
          <div className="details-upload-button-box">
            <Button
              className="p-2 mr-2 primary-button"
              onClick={handleUploadDoc}
              labelText="Upload Discovery Request"
            />
          </div>
        </div>
      </div>
    );
  };

  if (!group) {
    return null;
  }

  const HeadingContent = () => {
    return (
      <div className="details-heading-container">
        <h3 className="details-heading">Case Information:</h3>
        <div className="details-subhead">
          <h3 className="details-heading2">
            {subCase?.caption} v. {subCase?.captionTwo}
          </h3>
          <div className="pheno-phun">
            <h3 className="details-heading3">Index Number:</h3>
            <h3 className="details-heading4">{subCase?.caseNumber}</h3>
          </div>
        </div>
      </div>
    );
  };

  const showUp = showUploadModal && subCase !== null ? true : false;
  const showCreate = showCreateModal && subCase !== null ? true : false;
  const showConfirm = showConfirmModal && subCase !== null ? true : false;
  return (
    <div className="details-container">
      {isLoading ? <LoadingSpinner message={message} /> : null}
      {!isLoading ? <HeadingContent /> : null}
      {!isLoading ? (
        showUp ? (
          <UploadModal
            setShowModal={setShowUploadModal}
            setIsLoading={setIsLoading}
            handleSuccess={handleSuccess}
            caseData={subCase}
            handleConfirmDocType={handleConfirmDocType}
            fbUserId={fbUserId}
            clientPosition={subCase.clientPosition}
            uploadType={uploadType}
          />
        ) : null
      ) : null}
      {!isLoading ? (
        showCreate ? (
          <CreateModal setShowModal={setShowCreateModal} caseData={subCase} />
        ) : null
      ) : null}
      {!isLoading ? (
        showConfirm ? (
          <ConfirmModal
            setShowModal={setShowConfirmModal}
            onCancel={handleCancelConfirm}
            onConfirm={handleConfirmUpgrade}
            modalText="You have used the maximum documents allowed in your current subscription. Upgrade to get more."
            titleText="No documents remaining"
            buttonLabelText="Upgrade"
          />
        ) : null
      ) : null}
      {!isLoading ? (
        subCase !== null ? (
          <DetailCard data={subCase} />
        ) : null
      ) : null}
      {!isLoading ? <ButtonContent /> : null}
    </div>
  );
};

export default CaseDetailsPage;
//
