import { useState, useContext, useEffect } from "react";
import NewYorkCaption from "./captionHeaders/newYorkCaption.js";
import NewJerseyCaption from "./captionHeaders/newJerseyCaption.js";
import FloridaCaption from "./captionHeaders/floridaCaption.js";
import MichiganCaption from "./captionHeaders/michiganCaption.js";
import { useParams } from "react-router-dom";
import { Link, useNavigate } from "react-router-dom";
import EditElement from "../../pageElements/EditElement";
import { db } from "../../firebase";
import { AppContext } from "../../Hooks/useContext/appContext";
import Button from "../../pageElements/Button";
import ConfirmModal from "../Modals/ConfirmModal";
import LoadingSpinner from "../../pageElements/LoadingSpinner";
import { docEditCopy } from "../../Constants/Copy/docEditCopy.js";
import { doc, getDoc, updateDoc, increment } from "firebase/firestore";
import "../../styles/docedit-page.scss";

const DocEditPage = (props) => {
  const navigate = useNavigate();
  const { documentId, caseId, docType, clientPosition, responseGenerations } =
    useParams();
  const [document, setDocument] = useState(null);
  const [_docType, setDocType] = useState(docType);
  const [fetchedCase, setFetchedCase] = useState(null);
  const [parsedRogs, setParsedRogs] = useState([]);
  const [responses, setResponses] = useState([]);
  const [showInputEle, setShowInputEle] = useState(true);
  const { appState } = useContext(AppContext);
  const { group } = appState;
  const appUserId = group ? group.appUserId : null;
  const [isBusy, setIsBusy] = useState(false);
  const fbUserId = group ? group.fbAuthUid : null;
  const [showSaveModal, setShowSaveModal] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [isReport, setIsReport] = useState(false);
  const [issueText, setIssueText] = useState("");
  const [showErrorModal, setShowErrorModal] = useState(false);
  const [responsesCreated, setResponsesCreated] = useState(
    parseInt(responseGenerations)
  );
  // For document generation:
  const state = group?.state[0] ? group.state[0].code : "ny";
  const lawFirm = group ? group?.firm : null;
  const streetAdd = group ? group?.streetAddress : null;
  const city = group ? group?.city : null;
  const usState = group?.state[0] ? group?.state[0].code : "ny";
  const zipCode = group ? group?.zipCode : null;
  const telephone = group ? group?.telephone : null;
  const respondent =
    fetchedCase?.clientPosition == "Defendant"
      ? fetchedCase?.defendantParties
      : fetchedCase?.plaintiffParties;

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

  const displayCopy =
    state === "ny"
      ? docEditCopy.NewYork
      : state === "mi"
      ? docEditCopy.Michigan
      : state === "nj"
      ? docEditCopy.NewJersey
      : docEditCopy.NewJersey;

  const headerPicker = () => {
    switch (state) {
      case "ny":
        return (
          <NewYorkCaption
            displayCopy={displayCopy}
            fetchedCase={fetchedCase}
            onScrollClick={onScrollClick}
          />
        );
      case "nj":
        return (
          <NewJerseyCaption
            displayCopy={displayCopy}
            fetchedCase={fetchedCase}
            onScrollClick={onScrollClick}
          />
        );
      case "fl":
        return (
          <FloridaCaption
            displayCopy={displayCopy}
            fetchedCase={fetchedCase}
            onScrollClick={onScrollClick}
          />
        );
      case "mi":
        return (
          <MichiganCaption
            displayCopy={displayCopy}
            fetchedCase={fetchedCase}
            onScrollClick={onScrollClick}
          />
        );
      default:
        return (
          <NewYorkCaption
            displayCopy={displayCopy}
            fetchedCase={fetchedCase}
            onScrollClick={onScrollClick}
          />
        );
    }
  };

  const headerString =
    docType === "interrogatories" ? (
      "Response to Interrogatories"
    ) : docType === "admissions" ? (
      "Response to Request for Admissions"
    ) : docType === "production" ? (
      "Response to Request for Production"
    ) : docType === "combined-numbered" ? (
      "Response to Interrogatories and Request for Production"
    ) : (
      <></>
    );

  const servingParty =
    fetchedCase?.clientPosition === "Defendant"
      ? fetchedCase?.plaintiffParties
      : fetchedCase?.defendantParties;

  const messages = [
    "Generating responses. Please be patient, this may take several minutes.",
  ];

  async function getDocument(docId) {
    try {
      const docRef = doc(db, "documents", `${docId}`);
      const docSnap = await getDoc(docRef);
      if (docSnap.exists()) {
        const data = docSnap?.data();
        return data;
      } else {
        console.log("DB item does not exist");
      }
    } catch (error) {
      console.log(`A system error has occurred: ${error}`);
    }
  }

  async function getCase(caseId) {
    try {
      const docRef = doc(db, "cases", `${caseId}`);
      const docSnap = await getDoc(docRef);
      if (docSnap.exists()) {
        const _case = docSnap?.data();
        _case.id = docSnap._key.path.segments[1];
        setFetchedCase(_case);
      } else {
        console.log("DB item does not exist");
      }
    } catch (error) {
      console.log(`A system error has occurred: ${error}`);
    }
  }

  async function getParsedRequests(documentId, docType) {
    if (!documentId || !docType) {
      return;
    }
    try {
      const response = await fetch(
        `${apiUrl}/v1/get-parsed-requests/${documentId}/${docType}`,
        {
          method: "GET",
        }
      );
      const res = await response.json();

      const req = res[0].requests;
      if (req.length > 1) {
        setParsedRogs(req);
      }
    } catch (err) {
      console.log("Error occured:", err);
    }
  }

  useEffect(() => {
    if (!documentId) {
      return;
    }
    getDocument(documentId)
      .then((data) => {
        setDocument(data);
        const tempType = data?.docType;
        return tempType;
      })
      .then((type) => {
        setDocType(type);
      });
  }, [documentId]);

  useEffect(() => {
    if (!caseId) {
      return;
    }
    getCase(caseId);
  }, [caseId, documentId]);

  useEffect(() => {
    getParsedRequests(documentId, docType);
  }, [documentId, docType]);

  async function getCompletions(docId, docType) {
    if (!docId || !docType) {
      return;
    }

    const response = await fetch(
      `${apiUrl}/v1/get-completions/${docId}/${docType}`,
      {
        method: "GET",
      }
    );
    const resp = await response.json();
    return resp;
  }

  async function generateRespIncominIrregDiscReq(docId, clientPosition) {
    const isRequests = true;
    try {
      fetch(
        `${apiUrl}/v1/generate-disc-responses-irreg/${documentId}/${docType}/${isRequests}`,
        {
          method: "GET",
        }
      )
        .then(function (response) {
          return response.json();
        })
        .then((data) => {
          const respArray = data[0].responses;
          const result = respArray?.map((item, index) => {
            let obj = {};
            obj["showInputEle"] = false;
            obj["resp"] = item?.text;
            obj["index"] = index;
            return obj;
          });
          setResponses(result);
          updateRespGenerationCount(docId);
          setIsLoading(false);
        })
        .catch((err) => console.log(err));
    } catch (err) {
      console.log("gen/esp inresp err", err);
    }
  }

  async function updateRespGenerationCount(docId) {
    await updateDoc(doc(db, "documents", docId), {
      responseGenerations: increment(1),
    });
    setResponsesCreated((responsesCreated) => responsesCreated + 1);
  }

  useEffect(() => {
    if (!docType) {
      return;
    }
    if (docType != "combined-numbered") {
      return;
    }
    if (docType == "combined-numbered") {
      setIsLoading(true);
      generateRespIncominIrregDiscReq(documentId, clientPosition);
    }
  }, [documentId, docType, docType]);

  useEffect(() => {
    if (!docType) {
      return;
    }
    if (docType != "combined-numbered") {
      setIsLoading(true);
      getCompletions(documentId, docType)
        .then((data) => {
          const resp = data[0].responses.map((item, index) => {
            // NEVER CHANGE THIS:
            return { showInputEle: false, resp: item?.text, index: index };
          });
          setResponses(resp);
          setIsLoading(false);
        })
        .catch((err) => console.log(err));
    }
  }, [documentId, docType]);

  async function postEditedResponses(docId, docType) {
    let obj = {};
    obj["type"] = docType;
    obj["id"] = docId;
    obj["requests"] = responses ? responses : null;
    const data = JSON.stringify(obj);
    try {
      const response = await fetch(`${apiUrl}/v1/store-edited-completions`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        json: true,
        body: data,
      });
      const res = response;
      return res;
    } catch (error) {
      console.error("Error sending resp to server:", error);
    }
  }

  async function cleanUpDocx() {
    const docId = documentId;
    fetch(`${apiUrl}/cleanUpDocx/${docId}`, {
      method: "GET",
    })
      .then((response) => {
        //
      })
      .catch((err) => {
        console.log(err);
      });
  }

  async function createAndReturnDocx() {
    setIsBusy(true);
    const response = await handleCreateDocx();

    if (response?.status != 500) {
      setTimeout(getDocx, 5000);
      setTimeout(cleanUpDocx, 10000);
    } else {
      setShowErrorModal(true);
    }
    window.scrollTo(0, 0);
    setTimeout(setIsBusy, 4000, false);
    //setIsBusy(false);
  }

  async function getDocx() {
    const docId = documentId;
    const reqType = docType;
    fetch(`${apiUrl}/v1/get-docx/${docId}/${reqType}`, {
      method: "GET",
    }).then((response) => {
      response.blob().then((blob) => {
        let url = window.URL.createObjectURL(blob);
        let a = window.document.createElement("a");
        a.href = url;
        a.download = `${reqType}-repsonse.docx`;
        a.click();
      });
    });
  }

  async function postDocxData(obj) {
    const docId = documentId;
    const response = await fetch(`${apiUrl}/v1/store-docx-data/${docId}`, {
      method: "POST",
      body: JSON.stringify(obj),
    });
    //return res;
  }

  async function handleCreateDocx() {
    // TODO: compare to see if any changes made before gen, save those
    const docId = documentId;
    const leadAttorneys = fetchedCase?.leadAttorneys
      ? fetchedCase?.leadAttorneys
      : null;
    const reqType = docType;
    const captionOne = fetchedCase?.caption;
    const captionTwo = fetchedCase?.captionTwo;
    const caseNum = fetchedCase?.caseNumber;
    const plaintiffs = fetchedCase?.plaintiffParties;
    const defendants = fetchedCase?.defendantParties;
    const venued = fetchedCase?.venue;
    const juris = fetchedCase?.jurisdiction;
    const judge = fetchedCase?.judge;
    const clientPosition = fetchedCase?.clientPosition
      ? fetchedCase?.clientPosition
      : null;
    const currentRequestType = docType;
    try {
      const response = await fetch(`${apiUrl}/v1/store-docx-data/${docId}`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          caseCaption1: captionOne,
          caseCaption2: captionTwo,
          caseNumber: caseNum,
          clientPosition: clientPosition,
          currentRequestType: currentRequestType,
          defendant: defendants,
          firm: lawFirm,
          firmCity: city,
          firmState: usState.code,
          firmStreetAddress: streetAdd,
          firmZip: zipCode,
          judge: judge,
          jurisdiction: juris,
          leadAttorneys: leadAttorneys,
          plaintiff: plaintiffs,
          state: state,
          tel: telephone,
          venue: venued,
        }),
      });
      if (response.status === 200) {
        const resp = await fetch(
          `${apiUrl}/v1/generate-request-docx/${docId}`,
          {
            method: "POST",
            headers: {
              Accept: "application/json",
              "Content-Type": "application/json",
            },
          }
        );

        return resp;
      }
    } catch (err) {
      console.log("err in postDocxData", err);
    }
  }

  const handleConfirmReport = () => {
    setShowSaveModal(true);
    setIsReport(true);
  };

  const handleConfirmSave = () => {
    setShowSaveModal(true);
  };

  const handleSave = () => {
    postEditedResponses();
    setShowSaveModal(false);
  };

  const handleCancelSave = () => {
    setShowSaveModal(false);
  };

  const onScrollClick = () => {
    const bottom = window.document.scrollingElement.scrollHeight;
    const place = window.scrollY;
    if (place > bottom / 2) {
      window.scrollTo({ top: 0, behavior: "smooth" });
    } else if (place < bottom / 2) {
      window.scrollTo({ top: bottom, behavior: "smooth" });
    }
  };

  const numberingContent = (i) => {
    let numText;
    if (docType === "interrogatories") {
      numText = "INTERROGATORY NO..";
    } else if (docType === "admissions") {
      numText = "REQUEST FOR ADMISSION NO.";
    } else if (docType === "production") {
      numText = "REQUEST FOR PRODUCTION NO.";
    } else {
      numText = "REQUEST NO.";
    }
    return <div className="numbering-container">{`${numText}${i + 1}  `}</div>;
  };

  const handleBlur = (e, i) => {
    const newSelectedResponses = responses?.map((r) => {
      if (r.index === i) {
        return {
          ...r,
          showInputEle: !showInputEle,
        };
      }
      return r;
    });
    setResponses(newSelectedResponses);
  };

  const handleFocus = (arg, i) => {
    const newSelectedResponses = responses?.map((r) => {
      if (r.index === i) {
        return {
          ...r,
          showInputEle: !showInputEle,
        };
      }
      return r;
    });
    setResponses(newSelectedResponses);
  };

  const handleEditValue = (e, i) => {
    const editingRes = responses?.map((r) => {
      if (r.index === i) {
        return {
          ...r,
          resp: e.target.value,
        };
      }
      return r;
    });
    setResponses(editingRes);
  };

  const handleReport = () => {
    setShowSaveModal(false);
    setIsReport(false);
  };

  const handleBack = () => {
    navigate(`/documents`);
  };

  const editingContent = () => {
    return (
      <>
        <div> {headerPicker()}</div>
        <div className="doc-editing-wrapper">
          <div className="pleading-header">{headerString}</div>
          <div>
            {displayCopy.prelimaryStatement(docType, respondent, servingParty)}
          </div>
          <div className="doc-editing-sub-wrapper">
            {parsedRogs?.map((rog, i) => (
              <div className="req-item-outer-div">
                <div className="doced-request-text-up">
                  {numberingContent(i)}
                  {rog?.text}
                </div>
                <div className="req-item-inner-div">
                  <EditElement
                    value={
                      responses && responses.length > 2
                        ? // NEVER CHANGE THIS
                          responses[i].resp
                        : null
                    }
                    setShowInputEle={setShowInputEle}
                    showInputEle={
                      responses && responses.length > 2
                        ? responses[i].showInputEle
                        : null
                    }
                    handleFocus={handleFocus}
                    handleEditValue={handleEditValue}
                    handleBlur={handleBlur}
                    i={i}
                  />
                </div>
              </div>
            ))}
            <div
              className="docedit-report-container"
              onClick={() => handleConfirmReport()}
            >
              <div className="docedit-report-link">Report an issue</div>
            </div>
            <div className="doc-editing-button-container">
              <div className="generate-button-box">
                {/*  TODO: add tooltip: "This will save the document and create a .docx file that will (be downloaded?  saved somewhere?" */}
                <Button
                  className="primary-button create-gen-button"
                  onClick={createAndReturnDocx}
                  labelText={"Create .docx File"}
                />
              </div>
              <div className="details-button-box">
                <div>
                  <Button
                    className="pt-2 pb-2 mr-4 secondary-button edit-back-button"
                    onClick={handleBack}
                    labelText="Back To Documents Page"
                  />
                </div>
                <div>
                  <Button
                    className="pt-2 pb-2 mr-2 primary-button"
                    onClick={handleConfirmSave}
                    labelText="Save Changes"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
        {showSaveModal && !isReport && documentId !== null ? (
          <ConfirmModal
            onCancel={handleCancelSave}
            onConfirm={handleSave}
            buttonLabelText="Confirm Save"
            modalText={
              "Are you sure?  This will overrwrite any previously-saved edits."
            }
          />
        ) : null}
        {showSaveModal && isReport && documentId !== null ? (
          <ConfirmModal
            isReport={isReport}
            onCancel={handleCancelSave}
            onConfirm={handleReport}
            buttonLabelText="Report Issue"
            documentId={documentId}
            caseId={caseId}
            appUserId={appUserId}
            issuetext={issueText}
            setIssueText={setIssueText}
            modalText={
              "Date/time and document id automatically logged. Support will address this within 24 hours."
            }
          />
        ) : null}
        {showErrorModal ? (
          <ConfirmModal
            onCancel={() => setShowErrorModal(false)}
            onConfirm={() => setShowErrorModal(false)}
            buttonLabelText="Confirm"
            modalText={
              "There was a problem. Support was notified and will respond within 24 hours."
            }
          />
        ) : null}
      </>
    );
  };

  const readyToEdit = fetchedCase && responses.length > 1;

  return isLoading ? (
    <LoadingSpinner message={messages[0]} />
  ) : isBusy ? (
    <LoadingSpinner message={"Downloading .docx"} loaderType="MoonLoader" />
  ) : readyToEdit ? (
    editingContent()
  ) : (
    <div className="docedit-errstate-container">
      <div className="nodocs-text-container">
        <p>
          {" "}
          Response content for this document cannot be displayed at this time.
        </p>
        <p>Support has been notified and will respond within 24 hours.</p>
        <Link to="/dashboard">Return to Dashboard</Link>
      </div>
    </div>
  );
};

export default DocEditPage;
