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 { useNavigate } from "react-router-dom";
import { collection, setDoc, doc } from "firebase/firestore";
import { db } from "../../firebase";
import { v4 as uuidv4 } from "uuid";
import TextInput from "../../pageElements/TextInput";
import Radio from "../../pageElements/Radio";
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 } = 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 [showFileDetails, setShowFileDetails] = useState("");
  const [titleError, setShowTitleError] = useState("");
  const [docError, setShowDocError] = useState("");
  const fileTypes = ["PDF"];
  const fileName = fileToParse ? fileToParse.name : undefined;

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

  async function saveToDb(uuidName) {
    const createdAt = new Date();
    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: 0,
    };

    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) {
    try {
      const response = await fetch(`${apiUrl}/parseNewDoc`, {
        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) {
      setShowDocError("Please select a document to upload.");
      setShowTitleError("Please enter a document title");
      return;
    } else if (!docTitle) {
      setShowTitleError("Please enter a document title");
      return;
    } else if (!fileToParse) {
      setShowDocError("Please select a document to upload.");
      return;
    }

    try {
      const response = await processFile();
      console.log("response in upload modal", response);
      if (response.res?.status !== 200) {
        saveToDb(response.uuidName);
        return;
      } else {
        saveToDb(response.uuidName);
      }
    } catch (err) {
      console.log("err", err);
    }

    handleSuccess();
  }

  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>Document Upload</Modal.Title>
      </Modal.Header>
      <Modal.Body>
        <div className="modal-header-text-wrapper">
          <p className="upload-modal-header-text">
            Select a document in pdf format for upload. Enter the document title
            below. Document description is optional.
          </p>
          <p className="upload-modal-header-text">
            This document will be associated with {caption} v. {captionTwo}
            {caseNumber ? `, ${caseNumber}` : ""}.
          </p>
          <p className="upload-modal-header-text">
            If that is not the case you want to associate with this document,
            click "cancel", go back and select the intended case from your
            active case list.
          </p>
        </div>
        <Form>
          <Row>
            <Col className="mb-3">
              <TextInput
                key={"title"}
                name={"title"}
                value={docTitle}
                onChange={handleTitleInput}
                label={docTitle ? "" : "Title"}
                error={!!titleError}
                message={titleError}
              />
            </Col>
            <Col className="mb-3">
              <TextInput
                key={"description"}
                name={"description"}
                value={docDescription}
                onChange={handleDescInput}
                label="Description"
              />
            </Col>
          </Row>
          <Row>
            <Col className="mb-3">
              <TextInput
                key={"date"}
                name={"date"}
                value={dateServed}
                onChange={handleDateInput}
                label={dateServed ? "" : "Date Served"}
              />
            </Col>
            <Col />
          </Row>
          <Row>
            <Col className="mb-3">
              <Form.Label>Select Document</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 a 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}
        />
      </Modal.Footer>
    </Modal>
  );
};

export default UploadModal;
