import { useState, useContext } from "react";
import Button from "../../pageElements/Button";
import Form from "react-bootstrap/Form";
import Col from "react-bootstrap/Col";
import Row from "react-bootstrap/Row";
import TextInput from "../../pageElements/TextInput";
import Modal from "react-bootstrap/Modal";
import { v4 as uuidv4 } from "uuid";
import { collection, setDoc, updateDoc, doc } from "firebase/firestore";
import { AppContext } from "../../Hooks/useContext/appContext.js";
import { db } from "../../firebase";
import { objectMap } from "../../Utils/Object";
import { createCaseFields as fields } from "../../Constants/Fields/CreateCaseFields.js";
import {
  floridaCourts,
  michiganCourts,
  newYorkCounties,
} from "../../Constants/Fields/CreateCaseFields.js";
import "../../styles/modals.scss";
import {
  getFormDataDefaults,
  getValidatedFormData,
  handleFormDataChange,
  isFormDataHasErrors,
} from "../../Utils/Form";
import "../../styles/modals.scss";
import { useNavigate } from "react-router-dom";

const CreateModal = ({ setShowModal, caseData }) => {
  const { appState } = useContext(AppContext);
  const navigate = useNavigate();
  const { group } = appState;
  const appUserId = group.appUserId;
  const editCaseId = caseData?.id;
  const isEditing = typeof editCaseId !== "undefined";
  const [isBusy, setIsBusy] = useState(false);
  const [venueArray, setVenueArray] = useState();
  const [newCaseId, setNewCaseId] = useState();
  const state = group?.state[0].code ? group?.state[0].code : null;
  const caseNumCopy = state === "ny" ? "Index Number" : "Case Number";
  const [data, setData] = useState(
    getFormDataDefaults(fields, isEditing ? caseData : undefined)
  );

  const courtsList = state === "mi" ? michiganCourts : floridaCourts;
  function selectVenueValues(data) {
    const result = courtsList.filter((court) => {
      let val;
      const target = data?.jurisdiction?.value?.split(" ")[0];
      if (court?.circuit === target) {
        return court?.counties;
      }
    });
    const count = result[0]?.counties;
    return count;
  }

  const handleChangeInput = (e, name) => {
    let venArr;
    const newData = handleFormDataChange(e, name, data, fields);
    if (state === "fl" || state === "mi") {
      venArr = selectVenueValues(newData);
    }

    setVenueArray(venArr);
    if (newData !== null) {
      setData(newData);
    }
  };

  const validateData = () => {
    const newData = getValidatedFormData(data, fields);
    const hasErrors = isFormDataHasErrors(newData);
    setData(newData);
    return hasErrors ? null : objectMap(({ value }) => value, newData);
  };

  async function saveCaseData(dataValues) {
    if (isBusy) {
      return;
    }
    setIsBusy(true);
    if (isEditing) {
      try {
        await updateDoc(doc(db, "cases", editCaseId), dataValues);
        setShowModal(false);
      } catch (err) {
        console.log("Error updating case:", err);
      }
    } else {
      const caseId = uuidv4();
      const ownerId = appUserId; // userId;
      const caseData = {
        ownerId,
        caseId,
        ...dataValues,
      };
      try {
        const casesRef = collection(db, "cases");
        await setDoc(doc(casesRef, `${caseId}`), caseData);
        setShowModal(false);
        return caseId;
      } catch (err) {
        console.log("Error creating case:", err);
      }
    }
    setIsBusy(false);
  }

  const stateOfCase = "NY";

  const handleClose = () => {
    if (!isBusy) {
      setShowModal(false);
    }
  };

  const handleCreateCase = (e) => {
    e.preventDefault();
    const dataValues = validateData();
    let caseId;
    if (dataValues === null) {
      return;
    } else {
      try {
        saveCaseData(dataValues).then((res) => {
          const caseId = res;
          navigate(`/casetype/${caseId}`);
        });
      } catch (err) {
        console.log(err);
      }
    }
  };

  const modalInputForm = (
    <>
      <p className="create-modal-header">
        Please enter case information carefully. It will be used later when
        generating new documents.
      </p>
      <Form>
        <Row className="modal-caption-row">
          <Col style={{ marginBottom: "0px" }}>
            {isEditing ? (
              <div className="edit-modal-label">Case caption</div>
            ) : (
              <></>
            )}
            <div className="caption-one-container">
              <TextInput
                inputClassName={"create-modal-input"}
                key={"caption"}
                name={"caption"}
                value={data.caption.value}
                error={data.caption.error}
                message={data.caption.message}
                disabled={isBusy}
                onChange={(e) => handleChangeInput(e, "caption")}
                label={
                  data.caption.value.length === 0
                    ? isEditing
                      ? caseData.caption
                      : "Caption - Plaintiff(s)"
                    : ""
                }
              />
            </div>
          </Col>
          <div className="modal-caption-vee"> - v. -</div>
          <Col className="mb-3">
            {isEditing ? <span className="edit-modal-label"></span> : <></>}
            <TextInput
              key={"captionTwo"}
              name={"captionTwo"}
              value={data.captionTwo.value}
              error={data.captionTwo.error}
              message={data.captionTwo.message}
              disabled={isBusy}
              onChange={(e) => handleChangeInput(e, "captionTwo")}
              label={
                data.captionTwo.value.length === 0
                  ? isEditing
                    ? caseData.captionTwo
                    : "Caption - Defendant(s)"
                  : ""
              }
            />
          </Col>
        </Row>
        <Row>
          <Col className="mb-3">
            {isEditing ? (
              <div className="edit-modal-label">{caseNumCopy}</div>
            ) : (
              <></>
            )}
            <TextInput
              key={"caseNumber"}
              name={"caseNumber"}
              value={data.caseNumber.value}
              error={data.caseNumber.error}
              message={data.caseNumber.message}
              disabled={isBusy}
              onChange={(e) => handleChangeInput(e, "caseNumber")}
              label={
                data.caseNumber.value.length === 0
                  ? isEditing
                    ? caseData.caseNumber
                    : caseNumCopy
                  : ""
              }
            />
          </Col>
          <Col className="mb-3">
            {isEditing ? (
              <div className="edit-modal-label">Jurisdiction</div>
            ) : (
              <></>
            )}
            <TextInput
              key={"jurisdiction"}
              name={"jurisdiction"}
              state={state}
              value={data.jurisdiction.value}
              values={courtsList}
              error={data.jurisdiction.error}
              message={data.jurisdiction.message}
              type={state === "fl" || state === "mi" ? "select" : "text"}
              disabled={isBusy}
              onChange={(e) => handleChangeInput(e, "jurisdiction")}
              label={
                data.jurisdiction.value.length === 0
                  ? isEditing
                    ? caseData.jurisdiction
                    : "Jurisdiction"
                  : ""
              }
            />
          </Col>
        </Row>
        <Row>
          <Col className="mb-3">
            {isEditing ? <div className="edit-modal-label">Judge</div> : <></>}
            <TextInput
              key={"judge"}
              name={"judge"}
              value={data.judge.value}
              error={data.judge.error}
              message={data.judge.message}
              disabled={isBusy}
              onChange={(e) => handleChangeInput(e, "judge")}
              label={
                data.judge.value.length === 0
                  ? isEditing
                    ? caseData.judge
                    : "Judge"
                  : ""
              }
            />
          </Col>

          <Col className="mb-3">
            {isEditing ? <div className="edit-modal-label">Venue</div> : <></>}
            <TextInput
              key={"venue"}
              name={"venue"}
              value={data.venue.value}
              error={data.venue.error}
              type={state === "fl" || state === "mi" ? "select" : "text"}
              values={venueArray}
              message={data.venue.message}
              disabled={isBusy}
              onChange={(e) => handleChangeInput(e, "venue")}
              label={
                data.venue.value.length === 0
                  ? isEditing
                    ? caseData.venue
                    : "Venue"
                  : ""
              }
            />
          </Col>
        </Row>
        <Row>
          <Col className="mb-3">
            {isEditing ? (
              <div className="edit-modal-label">Trial Date</div>
            ) : (
              <></>
            )}
            <TextInput
              key={"trialDate"}
              name={"trialDate"}
              value={data.trialDate.value}
              error={data.trialDate.error}
              message={data.trialDate.message}
              disabled={isBusy}
              onChange={(e) => handleChangeInput(e, "trialDate")}
              label={
                data.trialDate.value.length === 0
                  ? isEditing
                    ? caseData.trialDate
                    : "Trial Date"
                  : ""
              }
            />
          </Col>

          <Col className="mb-3">
            {isEditing ? (
              <div className="edit-modal-label">Date filed</div>
            ) : (
              <></>
            )}
            <TextInput
              key={"filedDate"}
              name={"filedDate"}
              value={data.filedDate.value}
              error={data.filedDate.error}
              message={data.filedDate.message}
              disabled={isBusy}
              onChange={(e) => handleChangeInput(e, "filedDate")}
              label={
                data.filedDate.value.length === 0
                  ? isEditing
                    ? caseData.filedDate
                    : "Date Filed"
                  : ""
              }
            />
          </Col>
        </Row>
        <Row>
          <Col className="mb-3">
            {isEditing ? (
              <div className="edit-modal-label">Defendant(s)</div>
            ) : (
              <></>
            )}
            <TextInput
              key={"defendantParties"}
              name={"defendantParties"}
              value={data.defendantParties.value}
              error={data.defendantParties.error}
              message={data.defendantParties.message}
              disabled={isBusy}
              onChange={(e) => handleChangeInput(e, "defendantParties")}
              label={
                data.defendantParties.value.length === 0
                  ? isEditing
                    ? caseData.defendantParties
                    : "Defendant Parties"
                  : ""
              }
            />
          </Col>
          <Col className="mb-3">
            {isEditing ? (
              <div className="edit-modal-label">Plaintiff(s)</div>
            ) : (
              <></>
            )}
            <TextInput
              key={"plaintiffParties"}
              name={"plaintiffParties"}
              value={data.plaintiffParties.value}
              error={data.plaintiffParties.error}
              message={data.plaintiffParties.message}
              disabled={isBusy}
              onChange={(e) => handleChangeInput(e, "plaintiffParties")}
              label={
                data.plaintiffParties.value.length === 0
                  ? isEditing
                    ? caseData.plaintiffParties
                    : "Plaintiff Parties"
                  : ""
              }
            />
          </Col>
        </Row>
      </Form>
    </>
  );

  return (
    <Modal show="true" onHide={handleClose} size="lg">
      <Modal.Header closeButton>
        <Modal.Title>
          {isEditing ? "Edit case information" : "Enter case information"}
        </Modal.Title>
      </Modal.Header>
      <Modal.Body>{modalInputForm}</Modal.Body>
      <Modal.Footer>
        <Button
          className="secondary-button"
          disabled={isBusy}
          onClick={handleClose}
          labelText="Cancel"
        />
        <Button
          className="primary-button"
          disabled={isBusy}
          onClick={handleCreateCase}
          labelText="Save Case"
        />
      </Modal.Footer>
    </Modal>
  );
};

export default CreateModal;

/*
          <Col className="mb-3">
            {isEditing ? (
              <div className="edit-modal-label">Contact name</div>
            ) : (
              <></>
            )}
            <TextInput
              key={"contactName"}
              name={"contactName"}
              value={data.contactName.value}
              error={data.contactName.error}
              message={data.contactName.message}
              disabled={isBusy}
              onChange={(e) => handleChangeInput(e, "contactName")}
              label={
                data.contactName.value.length === 0
                  ? isEditing
                    ? caseData.contactName
                    : "Contact Name"
                  : ""
              }
            />
          </Col>

                    <Col className="mb-3">
            {isEditing ? (
              <div className="edit-modal-label">Case type</div>
            ) : (
              <></>
            )}
            <TextInput
              key={"caseType"}
              name={"caseType"}
              value={data.caseType.value}
              error={data.caseType.error}
              message={data.caseType.message}
              disabled={isBusy}
              onChange={(e) => handleChangeInput(e, "caseType")}
              label={
                data.caseType.value.length === 0
                  ? isEditing
                    ? caseData.caseType
                    : "Case Type"
                  : ""
              }
            />
          </Col>


            <Col>
            <div className="radio-group-wrapper">
              <Radiogroup
                title="Client position"
                options={radioOptions}
                value={data.clientPosition.value}
                disabled={isBusy}
                onClick={(e) => handleChangeInput(e, "clientPosition")}
              />
            </div>
          </Col>

          <Col className="mb-3">
            {isEditing ? (
              <div className="edit-modal-label">Billing code</div>
            ) : (
              <></>
            )}
            <TextInput
              key={"billingCode"}
              name={"billingCode"}
              value={data.billingCode.value}
              error={data.billingCode.error}
              message={data.billingCode.message}
              disabled={isBusy}
              onChange={(e) => handleChangeInput(e, "billingCode")}
              label={
                data.billingCode.value.length === 0
                  ? isEditing
                    ? caseData.billingCode
                    : "Billing Code"
                  : ""
              }
            />
          </Col>

                    <Col className="mb-3">
            {isEditing ? (
              <div className="edit-modal-label">Lead attorney</div>
            ) : (
              <></>
            )}
            <TextInput
              key={"leadAttorneys"}
              name={"leadAttorneys"}
              value={data.leadAttorneys.value}
              error={data.leadAttorneys.error}
              message={data.leadAttorneys.message}
              disabled={isBusy}
              onChange={(e) => handleChangeInput(e, "leadAttorneys")}
              label={
                data.leadAttorneys.value.length === 0
                  ? isEditing
                    ? caseData.leadAttorneys
                    : "Lead Attornery(s)"
                  : ""
              }
            />
          </Col>
          */
