import { useState, useContext, useEffect } from "react";
import headerPicker from "./HeaderPicker";
import { useParams } from "react-router-dom";
import { Link, useNavigate } from "react-router-dom";
import { AppContext } from "../../Hooks/useContext/appContext";
import EditElement from "../../pageElements/EditElement";
import LoadingSpinner from "../../pageElements/LoadingSpinner";
import {
  docEditCopy,
  outgoingComesNow,
} from "../../Constants/Copy/docEditCopy.js";
import Button from "../../pageElements/Button";
import {
  rogInstructions,
  rogDefinitions,
  foundationRogs,
  standardProd,
} from "../../Constants/Copy/reqEditCopy.js";
import { db } from "../../firebase";
import { doc, getDoc } from "firebase/firestore";
import "../../styles/doclist-page.scss";

const RequestEditPage = () => {
  const { documentId, documentType, caseId } = useParams();
  const { appState } = useContext(AppContext);
  const { group } = appState;
  const navigate = useNavigate();
  const [requests, setRequests] = useState([1]);
  const [prodReq, setProdReq] = useState();
  const [fetchedCase, setFetchedCase] = useState();
  const [showInputEle, setShowInputEle] = useState(true);
  const [showprodInputEle, setShowprodInputEle] = useState(true);
  const [document, setDocument] = useState(null);
  const appUserId = group ? group?.appUserId : null;
  const [docId, setDocId] = useState(documentId);
  const [saveDocumentId, setSaveDocumentId] = useState("");
  const [showSaveModal, setShowSaveModal] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [isReport, setIsReport] = useState(false);
  const [showErrorModal, setShowErrorModal] = useState(false);
  const [isBusy, setIsBusy] = useState(false);

  // Case Vars
  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 apiUrl =
    process.env.NODE_ENV === "development"
      ? process.env.REACT_APP_API_DEV
      : process.env.REACT_APP_API_PROD;

  useEffect(() => {
    if (!appUserId || !documentId) {
      setDocument(null);
      return;
    }
    try {
      getCase(caseId);
      //getDocument();
    } catch (err) {
      console.log("Error:", err);
    }
  }, [appUserId, documentId, caseId]);

  useEffect(() => {
    if (!documentId) {
      return;
    }
    getOutgoingRequests(documentId)
      .then((data) => {
        const merged = [...foundationRogs, ...data[0].requests];
        const resp = merged?.map((item, index) => {
          // NEVER CHANGE THIS:
          return { showInputEle: false, text: item.text, index: index };
        });
        if (resp.length > 10) {
          setRequests(resp);
          setProdReq(standardProd);
        }
      })
      .catch((err) => console.log(err));
  }, [documentId]);

  async function getCase(parentCaseId) {
    try {
      const docRef = doc(db, "cases", `${parentCaseId}`);
      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 getOutgoingRequests(documentId) {
    if (!documentId) {
      return;
    }
    const docType = String(documentType);
    const docId = String(documentId);
    const response = await fetch(
      `${apiUrl}/v1/get-outgoing-requests/${docId}/${docType}`,
      {
        method: "GET",
      }
    );
    const req = await response.json();
    return req;
  }

  async function getDocx() {
    const docId = documentId;
    const reqType = documentType;
    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 = `interrogatories-req-prod.docx`;
        a.click();
      });
    });
  }

  async function cleanUpDocx() {
    const docId = documentId;
    const reqType = documentType;
    fetch(`${apiUrl}/cleanUpDocx/${docId}/${reqType}`, {
      method: "GET",
    })
      .then((response) => {
        setIsBusy(false);
      })
      .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);
  }

  const postEditedrequests = () => {};

  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" });
    }
  };

  async function postEditedResponses() {
    if (!requests && requests.length > 1) {
      return;
    }
    const mergedRequests = [...requests, ...prodReq];
    const docId = documentId;
    const leadAttorneys = fetchedCase?.leadAttorneys
      ? fetchedCase?.leadAttorneys
      : null;
    const reqType = documentType;
    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 caseInfo = {
      caseCaption1: captionOne,
      caseCaption2: captionTwo,
      caseNumber: caseNum,
      clientPosition: clientPosition,
      currentRequestType: reqType,
      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,
    };

    let obj = {};
    obj["type"] = "interrogatories-out";
    obj["id"] = docId;
    obj["requests"] = mergedRequests;
    obj["caseInfo"] = caseInfo;

    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,
      });
      return response;
    } catch (error) {
      console.error("Error sending responses to the server:", error);
    }
  }

  async function handleCreateDocx(docType) {
    // 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 = "interrogatories-out";
    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 handleBlur = (e, i) => {
    const newSelectedrequests = requests?.map((r) => {
      if (r.index === i) {
        return {
          ...r,
          showInputEle: !showInputEle,
        };
      }
      return r;
    });
    setRequests(newSelectedrequests);
  };

  const handleProdBlur = (e, i) => {
    const newSelectedrequests = requests?.map((r) => {
      if (r.index === i) {
        return {
          ...r,
          showInputEle: !showInputEle,
        };
      }
      return r;
    });
    setRequests(newSelectedrequests);
  };

  const handleFocus = (arg, i) => {
    const newSelectedrequests = requests?.map((r) => {
      if (r.index === i) {
        return {
          ...r,
          showInputEle: !showInputEle,
        };
      }
      return r;
    });
    setRequests(newSelectedrequests);
  };

  const handleProdFocus = (arg, i) => {
    const newSelectedrequests = requests?.map((r) => {
      if (r.index === i) {
        return {
          ...r,
          showInputEle: !showInputEle,
        };
      }
      return r;
    });
    setRequests(newSelectedrequests);
  };

  const handleEditValue = (e, i) => {
    const editingRes = requests?.map((r) => {
      if (r.index === i) {
        return {
          ...r,
          text: e.target.value,
        };
      }
      return r;
    });
    setRequests(editingRes);
  };

  const handleEditProdValue = (e, i) => {
    const editingProd = standardProd?.map((r) => {
      if (r.index === i) {
        return {
          ...r,
          text: e.target.value,
        };
      }
      return r;
    });
    setProdReq(editingProd);
  };

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

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

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

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

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

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

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

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

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

  const editingContent = () => {
    return (
      <>
        <div> {headerPicker(state, fetchedCase, onScrollClick)}</div>
        <div className="doc-editing-wrapper">
          <div className="pleading-header">
            INTERROGATORIES AND REQUESTS FOR PRODUCTION
          </div>
          <div className="req-edit-comesnow-box">
            {outgoingComesNow(state, fetchedCase)}
          </div>
          {/*displayCopy.prelimaryStatement*/}
          <div className="request-editing-sub-wrapper row">
            <div className="pleading-header">INSTRUCTIONS</div>
            {rogInstructions?.map((req, i) => (
              <div className="request-text-up-row">
                <div className="request-text-number-col">{`${i + 1}.`}</div>
                <div>{req?.text}</div>
              </div>
            ))}
          </div>
          <div className="request-editing-sub-wrapper row">
            <div className="pleading-header">DEFINITIONS</div>
            {rogDefinitions?.map((req, i) => (
              <div className="request-text-up-row">
                <div className="request-text-number-col">{`${i + 1}.`}</div>
                <div>{req?.text}</div>
              </div>
            ))}
          </div>
          <div className="request-editing-sub-wrapper row">
            <div className="pleading-header">INTERROGATORIES</div>
            {requests?.map((req, i) => (
              <div className="request-text-up-row">
                <div className="request-text-number-col-low">{`${i + 1}.`}</div>
                <div className="req-edit-wrapper">
                  <div className="req-item-inner-div">
                    <EditElement
                      value={
                        requests && requests.length > 2
                          ? // NEVER CHANGE THIS
                            req.text
                          : null
                      }
                      setShowInputEle={setShowInputEle}
                      showInputEle={
                        requests && requests.length > 2
                          ? req.showInputEle
                          : null
                      }
                      handleFocus={handleFocus}
                      handleEditValue={handleEditValue}
                      handleBlur={handleBlur}
                      i={i}
                    />
                  </div>
                </div>
              </div>
            ))}
          </div>
          <div className="request-editing-sub-wrapper row">
            <div className="pleading-header">REQUESTS FOR PRODUCTION</div>
            {prodReq?.map((preq, i) => (
              <div className="request-text-up-row">
                <div className="request-text-number-col">{`${i + 1}.`}</div>
                <div className="req-edit-wrapper">
                  <div className="req-item-inner-div">
                    <EditElement
                      value={
                        standardProd && standardProd.length > 2
                          ? // NEVER CHANGE THIS
                            preq.text
                          : null
                      }
                      setShowInputEle={setShowInputEle}
                      showInputEle={
                        standardProd && standardProd.length > 2
                          ? preq.showInputEle
                          : null
                      }
                      handleFocus={handleFocus}
                      handleEditValue={handleEditValue}
                      handleBlur={handleBlur}
                      i={i}
                    />
                  </div>
                </div>
              </div>
            ))}
          </div>
          <div
            className="reqedit-report-container"
            onClick={() => handleConfirmReport()}
          >
            <div className="docedit-report-link">Report an issue</div>
          </div>
          <div className="req-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>
      </>
    );
  };

  //const readyToEdit = fetchedCase && requests.length > 1;
  const readyToEdit = true;
  const messages = [
    "Generating responses. Please be patient, this may take several minutes.",
  ];

  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> 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 RequestEditPage;

/*

  async function handleCreateDocx() {
    const res = await postEditedResponses();
    function sleep(ms) {
      return new Promise((resolve) => setTimeout(resolve, ms));
    }
    await sleep(2000);
    try {
      const response = await fetch(
        `${apiUrl}/v1/generate-request-docx/${docId}`,
        {
          method: "POST",
          headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            docId: docId,
          }),
        }
      );
      return response;
    } catch (error) {
      console.error("Error sending requests to the server:", error);
    }
  }
  */
