import React, { useEffect, useContext, useState, useRef } from "react";
import { useNavigate } from "react-router-dom";
import { useParams } from "react-router-dom";
import { Typeahead } from "react-bootstrap-typeahead";
import { AppContext } from "../../Hooks/useContext/appContext.js";
import { updateDoc, doc, onSnapshot } from "firebase/firestore";
import Button from "../../pageElements/Button";
import Radiogroup from "../../pageElements/Radiogroup";
import { caseTags } from "../../Constants/Tags/CaseTags";
import { db } from "../../firebase";
import "../../styles/casetype-page.scss";

const CaseTypePage = () => {
  const { caseId } = useParams();
  const navigate = useNavigate();
  const { appState } = useContext(AppContext);
  const { group } = appState;
  const appUserId = group ? group.appUserId : null;
  const [subCase, setSubCase] = useState();
  const [contactEmail, setContactEmail] = useState("");
  const [contactName, setContactName] = useState("");
  const [billingCode, setBillingCode] = useState("");
  const [leadAttorney, setLeadAttorney] = useState("");
  const [radioValue, setRadioValue] = useState("");
  const [selectedCaseTags, setSelectedCaseTags] = useState([]);
  const [isBusy, setIsBusy] = useState(false);
  const [contactEmailError, setContactEmailError] = useState("");
  const [leadAttorneyError, setLeadAttorneyError] = useState("");
  const [caseTypeError, setCaseTypeError] = useState(false);
  const [clientPositionError, setClientPositionError] = useState();
  const typeaheadRef = useRef();

  function getCase() {
    const docRef = doc(db, "cases", caseId);
    const unsub = onSnapshot(docRef, (snapshot) => {
      if (snapshot.exists() && snapshot.data().ownerId === appUserId) {
        setSubCase({ ...snapshot.data(), id: snapshot.id });
      } else {
        setSubCase(null);
      }
    });
    return unsub;
  }

  const parsedTags = JSON.parse(JSON.stringify(caseTags));

  useEffect(getCase, [caseId, appUserId]);

  const setSelectedTag = (item) => {
    if (selectedCaseTags.length < 5) {
      const temp = [...selectedCaseTags, item.tagName];
      setSelectedCaseTags(temp);
    }
  };

  const handleTagClick = (arg) => {
    const temp = selectedCaseTags;
    const foo = temp.filter((tag) => {
      if (tag != arg) {
        return tag;
      }
    });
    setSelectedCaseTags(foo);
  };

  const radioOptions = [
    { name: "Plaintiff", label: "Plaintiff", value: "Plaintiff" },
    { name: "Defendant", label: "Defendant", value: "Defendant" },
  ];

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

  const validateEmail = (email) => {
    const result = /.+@.+\.[A-Za-z]+$/.test(email);
    return result;
  };

  const validateInput = () => {
    const leadAttorneyValid = leadAttorney.length > 2;
    const contactEmailValid = validateEmail(contactEmail);
    const caseTypeValid = selectedCaseTags.length > 0;
    const clientPositionValid =
      radioValue === "Defendant" || radioValue === "Plaintiff";

    const allValid =
      leadAttorneyValid &&
      contactEmailValid &&
      caseTypeValid &&
      clientPositionValid;

    if (!leadAttorneyValid) {
      setLeadAttorneyError("Field cannot be left blank");
    }
    if (!contactEmailValid) {
      setContactEmailError("Field cannot be left blank");
    }
    if (!caseTypeValid) {
      setCaseTypeError("Field cannot be left blank");
    }
    if (!clientPositionValid) {
      setClientPositionError("You must make a selection");
    }

    return allValid;
  };

  async function saveCaseData() {
    if (isBusy) {
      return;
    }

    const valid = validateInput();

    if (valid) {
      const recordTags = [];
      selectedCaseTags.forEach((tag) => {
        parsedTags.forEach((item) => {
          if (item.tagName.toLowerCase() === tag.toLowerCase()) {
            recordTags.push(item);
          }
        });
      });

      const dataValues = {
        leadAttorney: leadAttorney,
        contactEmail: contactEmail,
        contactName: contactName,
        clientPosition: radioValue,
        caseTags: recordTags,
      };
      setIsBusy(true);
      try {
        await updateDoc(doc(db, "cases", caseId), dataValues);
        setIsBusy(false);
        navigate(`/casedetails/${caseId}`);
      } catch (err) {
        console.log("Error updating case:", err);
        setIsBusy(false);
        navigate(`/dashboard`);
      }
    }
  }

  return (
    <div className="type-container">
      <div
        clasName="casetype-header"
        style={{ marginTop: "22px", marginBottom: "12px" }}
      >
        <h3 className="doc-header-text">Additional Case Information</h3>
      </div>

      <div className="type-row">
        <div className="type-col">
          <input
            type="email"
            className="form-control"
            id="attorneyInput"
            placeholder="Lead Attorney"
            value={leadAttorney}
            onChange={(e) => setLeadAttorney(e.target.value)}
          ></input>
          <div>
            {leadAttorneyError ? (
              <div className="casetype-error">{leadAttorneyError}</div>
            ) : (
              <></>
            )}
          </div>
        </div>
        <div className="type-col">
          <input
            type="email"
            className="form-control"
            id="billingInput"
            placeholder="Billing Code"
            value={billingCode}
            onChange={(e) => setBillingCode(e.target.value)}
          ></input>
        </div>
      </div>
      <div className="type-row">
        <div className="type-col">
          <input
            type="email"
            className="form-control"
            id="emailInput"
            placeholder="Contact Name"
            value={contactName}
            onChange={(e) => setContactName(e.target.value)}
          ></input>
        </div>
        <div className="type-col">
          <input
            type="email"
            className="form-control"
            id="emailInput"
            placeholder="Contact Email"
            value={contactEmail}
            onChange={(e) => setContactEmail(e.target.value)}
          ></input>
          {contactEmailError ? (
            <div className="casetype-error">{contactEmailError}</div>
          ) : (
            <></>
          )}
        </div>
      </div>
      <div className="type-row">
        <div className="type-col create-case-taginput">
          <Typeahead
            className="flex-grow-1"
            id="case-type-search"
            labelKey="tagName"
            options={parsedTags}
            minLength={1}
            ref={typeaheadRef}
            placeholder="Case Type - type to search, tab/click to select (max 5)"
            onChange={(selected) => {
              let item = null;
              for (const currentItem of selected) {
                item = { ...currentItem };
              }
              setSelectedTag(item);
              typeaheadRef.current.clear();
            }}
          />
          {caseTypeError ? (
            <div className="casetype-error">{caseTypeError}</div>
          ) : (
            <></>
          )}
          <div className="case-tag-container">
            {selectedCaseTags.map((tag, i) => (
              <div className="tag-container">
                <div className="tag-box">
                  <div
                    className="tag-ex-box"
                    onClick={() => handleTagClick(tag)}
                  >
                    <div className="tag-ex">x</div>
                  </div>
                  <div className="casetag-name">{tag}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
        <div className="type-col">
          <div className="radio-wrapper">
            <Radiogroup
              title="Client position"
              options={radioOptions}
              value={radioValue}
              onClick={(e) => handleSetRadioValue(e, "clientPosition")}
            />
          </div>
          {clientPositionError ? (
            <div className="casetype-error">{clientPositionError}</div>
          ) : (
            <></>
          )}
        </div>
      </div>

      <div className="casetype-button-container">
        <Button
          className="pt-2 pb-2 mr-2 primary-button"
          onClick={saveCaseData}
          labelText="Next"
        />
      </div>
    </div>
  );
};

export default CaseTypePage;
