import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import TasksPageComponent from "./tasks.page.component";
import queryString from "query-string";

import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { setBreadcrumbs, setSelectedHeader } from "../../redux/application/application.actions";
import InstanceRenderManager from "../../utils/instanceRenderMgr.js";
import TaskPageTypes from "./taskPageTypes.jsx";
import { setModalContext } from "../../redux/modals/modals.actions.js";
import { useLocation } from "react-router-dom";

const mapStateToProps = createStructuredSelector({});

const mapDispatchToProps = (dispatch) => ({
  setBreadcrumbs: (breadcrumbs) => dispatch(setBreadcrumbs(breadcrumbs)),
  setSelectedHeader: (key) => dispatch(setSelectedHeader(key)),
  setTaskUpsertContext: (context) => dispatch(setModalContext({ context, modal: "taskUpsert" }))
});

export function AllTasksPageContainer({ setBreadcrumbs, setSelectedHeader, setTaskUpsertContext }) {
  const { t } = useTranslation();
  const searchParams = queryString.parse(useLocation().search);
  useEffect(() => {
    document.title = t("titles.all_tasks", {
      app: InstanceRenderManager({
        imex: "$t(titles.imexonline)",
        rome: "$t(titles.romeonline)"
      })
    });
    setSelectedHeader("all_tasks");
    setBreadcrumbs([
      {
        link: "/manage/tasks/alltasks",
        label: t("titles.bc.all_tasks")
      }
    ]);
  }, [t, setBreadcrumbs, setSelectedHeader]);

  // This takes care of the ability to deep link a task from the URL (Dispatches the modal)
  useEffect(() => {
    // Check for a query string in the URL
    const urlParams = new URLSearchParams(searchParams);
    const taskId = urlParams.get("taskid");
    if (taskId) {
      setTaskUpsertContext({
        context: {
          taskId,
          view: true
        }
      });
      urlParams.delete("taskid");
    }
  }, [setTaskUpsertContext, searchParams]);

  return <TasksPageComponent type={TaskPageTypes.ALL_TASKS} />;
}

export default connect(mapStateToProps, mapDispatchToProps)(AllTasksPageContainer);
