import React, { useEffect, useContext, useState, useRef } from "react";
import { useNavigate } from "react-router-dom";
import { CaseCard } from "../../pageElements/Cards.js";
import CreateModal from "../Modals/CreateModal.js";
import MobileContent from "../MobileContent.js";
import { db } from "../../firebase";
import { AppContext } from "../../Hooks/useContext/appContext";
import SelectDropdown from "../../pageElements/SelectDropdown";
import { collection, query, where, onSnapshot } from "firebase/firestore";
import ListPagination from "../../pageElements/ListPagination.js";
import Button from "../../pageElements/Button";

const CaseListPage = ({ perPage }) => {
  const size = window.innerWidth < 440;
  const [isMobile, setIsMobile] = useState(size);
  const count = useRef(null);
  const navigate = useNavigate();
  const [showModal, setShowModal] = useState(false);
  const [allCases, setAllCases] = useState(null);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [order, setOrder] = useState("caption");
  const { appState } = useContext(AppContext);
  const { group } = appState;
  const appUserId = group ? group.appUserId : null;
  const state = group ? group?.state[0].code : null;

  useEffect(() => {
    if (count.current == null) {
      setIsMobile(window.innerWidth < 440);
    }
    if (count.current < 3) {
      setIsMobile(window.innerWidth < 440);
    }
    return () => {
      const temp = (count.current = count.current + 1);
      count.current = temp;
    };
  }, []);

  function getCases() {
    if (!appUserId) {
      setAllCases([]);
      return;
    }
    const q = query(collection(db, "cases"), where("ownerId", "==", appUserId));
    const unsub = onSnapshot(q, (snapshot) => {
      const data = snapshot.docs.map((doc) => doc.data());
      if (order === "caption") {
        data.sort((a, b) => {
          return a.caption.toLowerCase() > b.caption.toLowerCase() ? 1 : -1;
        });
      } else if (order === "caption2") {
        data.sort((a, b) => {
          return a.caption.toLowerCase() < b.caption.toLowerCase() ? 1 : -1;
        });
      } else if (order === "filedDate") {
        data.sort((a, b) => {
          return a.filedDate > b.filedDate ? 1 : -1;
        });
      } else if (order === "filedDate2") {
        data.sort((a, b) => {
          return a.filedDate < b.filedDate ? 1 : -1;
        });
      }
      const pages = Math.ceil(data.length / perPage);
      if (page > pages) {
        setPage(pages);
      }
      setTotalPages(pages);
      setAllCases(data);
    });
    return unsub;
  }
  const createNewButton = () => {
    return (
      <div className="create-new-box">
        <Button
          className="primary-button"
          onClick={() => setShowModal(!showModal)}
          labelText="Create New Case"
        />
      </div>
    );
  };

  const dropDownOptions = [
    { label: "Case name a - z", value: "caption" },
    { label: "Case name z - a", value: "caption2" },
    { label: "Date filed 1 - 10", value: "filedDate" },
    { label: "Date filed 10 - 1", value: "filedDate2" },
  ];

  useEffect(getCases, [appUserId, order]);

  async function deleteData() {
    console.log("delete data");
  }

  const handleView = (caseId) => {
    navigate(`/casedetails/${caseId}`);
  };

  if (!group) {
    return null;
  }

  const DesktopContent = () => {
    return (
      <>
        <div className="doc-list-header">
          <h2 className="doc-header-text">Active Cases</h2>
          <div className="user-name-container" style={{ marginLeft: "4px" }}>
            {group.firm}
          </div>
        </div>
        {showModal ? <CreateModal setShowModal={setShowModal} /> : <></>}
        {allCases === null ? <div>Loading...</div> : null}
        {allCases !== null ? (
          allCases.length > 0 ? (
            <>
              <div className="d-flex justify-content-end mb-3">
                <SelectDropdown
                  dropDownOptions={dropDownOptions}
                  titleText="Sort Cases"
                  handleSelect={setOrder}
                />
              </div>
              <div>
                {allCases
                  .slice((page - 1) * perPage, page * perPage)
                  .map((c, i) => (
                    <CaseCard
                      key={`linkcard-${i}`}
                      caption={c.caption}
                      captionTwo={c.captionTwo}
                      jurisdiction={c.jurisdiction}
                      filedDate={c.filedDate}
                      caseNumber={
                        state === "ny"
                          ? `Index no. ${c.caseNumber}`
                          : `Case no. ${c.caseNumber}`
                      }
                      caseId={c.caseId}
                      labelText="View"
                      onClick={handleView}
                    />
                  ))}
              </div>
              {totalPages > 1 ? (
                <div className="mb-3">
                  <ListPagination
                    page={page}
                    totalPages={totalPages}
                    setPage={setPage}
                  />
                </div>
              ) : null}
              {createNewButton()}
            </>
          ) : (
            <div className="nodocs-text-container">
              <p> Please create your first case.</p>
              <p>
                To create a discovery request or response, you will first enter
                some basic information about the case they will pertain to -
                i.e. the caption and case number.
              </p>
              <p>
                Then, you will upload a document (i.e. interrogatories or a
                complaint), for use in generating a request/response.
              </p>
              <p>Click "Create New Case" to get started.</p>
              {createNewButton()}
            </div>
          )
        ) : null}
      </>
    );
  };

  return isMobile ? <MobileContent /> : <DesktopContent />;
};

export default CaseListPage;
