import React, { useState, useContext } from "react";
import { FileUploader } from "react-drag-drop-files";
import { AppContext } from "../../Hooks/useContext/appContext";
import Modal from "react-bootstrap/Modal";
import Button from "../../pageElements/Button";
import Form from "react-bootstrap/Form";
import Row from "react-bootstrap/Row";
import Col from "react-bootstrap/Col";
import Radiogroup from "../../pageElements/Radiogroup";
import {
  collection,
  setDoc,
  doc,
  updateDoc,
  increment,
} from "firebase/firestore";
import { db } from "../../firebase";
import { v4 as uuidv4 } from "uuid";
import TextInput from "../../pageElements/TextInput";
import { ExclamationTriangle } from "react-bootstrap-icons";
import "../../styles/modals.scss";

const MAX_LENGTH_TITLE = 27;
const MAX_LENGTH_DESC = 35;
const MAX_LENGTH_DATE = 20;

const UploadModal = (props) => {
  const { appState } = useContext(AppContext);
  const { group } = appState;
  const appUserId = group.appUserId;
  const {
    setShowModal,
    caseData,
    handleSuccess,
    setIsLoading,
    clientPosition,
    fbUserId,
    uploadType,
  } = props;
  const { caseId, caseNumber, jurisdiction, caption, captionTwo } = caseData;
  const [docTitle, setDocTitle] = useState("");
  const [docDescription, setDocDescription] = useState("");
  const [dateServed, setDateServed] = useState("");
  const [fileToUpload, setFileToUpload] = useState();
  const [fileToParse, setFileToParse] = useState("");
  const [fileChanged, setFileChanged] = useState();
  const [radioValue, setRadioValue] = useState(uploadType);
  const [radioValueError, setRadioValueError] = useState("");
  const [showFileDetails, setShowFileDetails] = useState("");
  const [titleError, setShowTitleError] = useState("");
  const [docError, setShowDocError] = useState("");
  const fileTypes = ["PDF"];
  const fileName = fileToParse ? fileToParse.name : undefined;

  const currentType =
    uploadType === "complaint" ? "complaint" : "discovery request";
  const otherType =
    uploadType === "complaint" ? "discovery request" : "complaint";
  let docType;
  const apiUrl =
    process.env.NODE_ENV === "development"
      ? process.env.REACT_APP_API_DEV
      : process.env.REACT_APP_API_PROD;

  const radioOptions = [
    {
      name: "Discovery request",
      label: "Discovery request",
      value: "discovery-request",
    },
    { name: "Complaint", label: "Complaint", value: "complaint" },
  ];

  const handleSetRadioValue = (e) => {
    setRadioValue(e.value);
  };

  async function updateUserAccountDocsGenerated(fbUserId) {
    await updateDoc(doc(db, "users", fbUserId), {
      docsGenerated: increment(1),
    });
  }

  async function saveToDb(uuidName) {
    const createdAt = new Date();
    let respGenVal;
    if (radioValue === "complaint") {
      respGenVal = 1;
    } else {
      respGenVal = 0;
    }
    const data = {
      ownerId: appUserId,
      createdAt: createdAt,
      documentName: `${uuidName}.pdf`,
      docDescription: docDescription,
      dateServed: dateServed,
      docTitle: docTitle,
      parentCaseId: caseId,
      parentCaseName: `${caption} v. ${captionTwo}`,
      parentCaseNumber: caseNumber,
      parentCaseJurisdiction: jurisdiction,
      responseGenerations: respGenVal,
      clientPosition: clientPosition,
    };

    if (radioValue === "complaint") {
      docType = "interrogatories-out";
      data["docType"] = docType;
      updateUserAccountDocsGenerated(fbUserId);
    }

    try {
      const documentsRef = collection(db, "documents");
      await setDoc(doc(documentsRef, `${uuidName}`), data);
    } catch (err) {
      console.log("Error saving case to db:", err);
    }
  }

  async function handleFileChange(file) {
    setFileToParse(file);
    setFileChanged(true);
  }

  async function uploadFile(file) {
    if (!clientPosition) {
      return;
    }

    try {
      if (radioValue.toLowerCase() === "complaint") {
        const response = await fetch(`${apiUrl}/v1/parse-new-compdoc`, {
          method: "POST",
          body: file,
        });
        const res = response;
        return res;
      } else {
        const response = await fetch(`${apiUrl}/v1/parse-new-req-doc`, {
          method: "POST",
          body: file,
        });
        const res = response;
        return res;
      }
    } catch (error) {
      console.error("Error:", error);
    }
  }

  async function processFile() {
    const uuidName = uuidv4();
    const newName = `${uuidName}.pdf`;
    const title = docTitle;
    const description = docDescription || "";
    const formData = new FormData();

    if (fileToParse && fileChanged) {
      formData.append("file", fileToParse[0], newName);
    }

    if (fileName) {
      formData.append("fileName", fileName);
    }

    formData.append("title", title);
    formData.append("description", description);
    setFileToUpload(formData);

    let response = {};

    const res = await uploadFile(formData);

    response["uuidName"] = uuidName;
    response["res"] = res;
    return response;
  }

  async function handleUpload() {
    if (!docTitle && !fileToParse && !radioValue) {
      setShowDocError("Please select a document to upload.");
      setShowTitleError("Please enter a document title");
      setRadioValueError("Please select document type");
      return;
    } else if (!docTitle) {
      setShowTitleError("Please enter a document title");
      return;
    } else if (!fileToParse) {
      setShowDocError("Please select a document to upload.");
      return;
    }
    setIsLoading(true);
    try {
      const response = await processFile();
      saveToDb(response.uuidName);
      const docId = response.uuidName;

      setTimeout(handleSuccess, 10000, docId, radioValue);
      return;
    } catch (err) {
      console.log("err", err);
    }
  }

  const handleUploadCancel = () => {
    setShowFileDetails(false);
    setFileToParse(null);
    setFileChanged(false);
    setShowModal(false);
  };

  const handleTitleInput = (e) => {
    if (e.target.value.length <= MAX_LENGTH_TITLE) {
      setDocTitle(e.target.value);
    }
  };

  const handleDescInput = (e) => {
    if (e.target.value.length <= MAX_LENGTH_DESC) {
      setDocDescription(e.target.value);
    }
  };

  const handleDateInput = (e) => {
    if (e.target.value.length <= MAX_LENGTH_DATE) {
      setDateServed(e.target.value);
    }
  };

  return (
    <Modal show="true" onHide={handleUploadCancel} size="lg">
      <Modal.Header closeButton>
        <Modal.Title>Upload {currentType}</Modal.Title>
      </Modal.Header>
      <Modal.Body>
        <div className="modal-header-text-wrapper">
          <p className="upload-modal-header-text">
            1, Enter document title, (i.e. Plaintiff's Interrogatories). 2.
            Click or drag and drop the .psf file.
          </p>
          <p className="upload-modal-header-text">
            The document created will be associated with{" "}
            <em>
              {caption} v. {captionTwo}
            </em>
            {caseNumber ? `, ${caseNumber}` : ""}.
          </p>
          <p className="upload-modal-header-text">
            If that is not the correct case: 1. click cancel 2. click back, then
            3. select correct case from active cases.
          </p>
          <p className="upload-modal-header-text red">
            <span className="upload-header-text">
              <ExclamationTriangle
                style={{
                  color: "red",
                  marginBottom: "6px",
                  marginRight: "8px",
                }}
              />
              YOU ARE UPLOADING A {currentType.toUpperCase()}.
              <p className="upload-modal-header-text indent">
                If you intended to upload a {otherType} - click "cancel", then
                select {otherType}
              </p>
            </span>
          </p>
        </div>
        <Form>
          <Row>
            <Col className="mb-3">
              <TextInput
                key={"title"}
                name={"title"}
                value={docTitle}
                onChange={handleTitleInput}
                label={
                  docTitle
                    ? ""
                    : `${
                        currentType.split("")[0].toUpperCase() +
                        currentType.substring(1, 20)
                      } title`
                }
                error={!!titleError}
                message={titleError}
              />
            </Col>
            <Col className="mb-3">
              <TextInput
                key={"description"}
                name={"description"}
                value={docDescription}
                onChange={handleDescInput}
                label={`${
                  currentType.split("")[0].toUpperCase() +
                  currentType.substring(1, 20)
                } description`}
              />
            </Col>
          </Row>
          <Row>
            <Col className="mb-3">
              <TextInput
                key={"date"}
                name={"date"}
                value={dateServed}
                onChange={handleDateInput}
                label={
                  dateServed
                    ? ""
                    : `${
                        currentType.split("")[0].toUpperCase() +
                        currentType.substring(1, 20)
                      } date served`
                }
              />
            </Col>
            <Col>
              <div></div>
            </Col>
          </Row>
          <Row className="file-upload-row">
            <Col className="mb-3">
              <Form.Label>Select {currentType}</Form.Label>
              <div className="file-uploader">
                <FileUploader
                  multiple={true}
                  handleChange={handleFileChange}
                  name="file"
                  types={fileTypes}
                >
                  <div className={fileToParse ? "drag-box filled" : "drag-box"}>
                    {fileToParse
                      ? fileToParse[0]?.name
                      : "Click to select file or drag and drop here"}
                  </div>
                </FileUploader>
              </div>
            </Col>
            {docError ? (
              <div className="modal-document-error">{docError}</div>
            ) : (
              <></>
            )}
          </Row>
        </Form>
      </Modal.Body>
      <Modal.Footer>
        <Button
          className="btn primary-button cancel-button"
          onClick={handleUploadCancel}
          labelText="Cancel"
        />
        <Button
          labelText="Upload"
          className="primary-button pr-1 pl-1"
          onClick={() => handleUpload(radioValue)}
        />
      </Modal.Footer>
    </Modal>
  );
};

export default UploadModal;

/*
                <Radiogroup
                  title="Document type"
                  options={radioOptions}
                  value={radioValue}
                  radioError={radioValueError}
                  onClick={(e) => handleSetRadioValue(e, "documentType")}
                />
                */
