import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import RbacWrapper from "../../components/rbac-wrapper/rbac-wrapper.component";
import { setBreadcrumbs, setSelectedHeader } from "../../redux/application/application.actions";
import PhonebookPage from "./phonebook.page.component";
import { Drawer, Grid } from "antd";
import { useLocation, useNavigate } from "react-router-dom";
import PhonebookFormContainer from "../../components/phonebook-form/phonebook-form.container";
import queryString from "query-string";
import InstanceRenderManager from "../../utils/instanceRenderMgr";

const mapDispatchToProps = (dispatch) => ({
  setBreadcrumbs: (breadcrumbs) => dispatch(setBreadcrumbs(breadcrumbs)),
  setSelectedHeader: (key) => dispatch(setSelectedHeader(key))
});

export function PhonebookContainer({ setBreadcrumbs, setSelectedHeader }) {
  const { t } = useTranslation();

  useEffect(() => {
    document.title = t("titles.phonebook", {
      app: InstanceRenderManager({
        imex: "$t(titles.imexonline)",
        rome: "$t(titles.romeonline)"
      })
    });
    setSelectedHeader("phonebook");
    setBreadcrumbs([
      {
        link: "/manage/phonebook",
        label: t("titles.bc.phonebook")
      }
    ]);
  }, [setBreadcrumbs, t, setSelectedHeader]);

  const search = queryString.parse(useLocation().search);
  const { phonebookentry } = search;

  const navigate = useNavigate();

  const screens = Grid.useBreakpoint();
  
  const bpoints = {
    xs: "100%",
    sm: "100%",
    md: "100%",
    lg: "50%",
    xl: "50%",
    xxl: "45%"
  };
  
  // Get the largest active breakpoint
  let drawerPercentage = "100%";
  if (screens.xxl) drawerPercentage = bpoints.xxl;
  else if (screens.xl) drawerPercentage = bpoints.xl;
  else if (screens.lg) drawerPercentage = bpoints.lg;
  else if (screens.md) drawerPercentage = bpoints.md;
  else if (screens.sm) drawerPercentage = bpoints.sm;
  else if (screens.xs) drawerPercentage = bpoints.xs;

  return (
    <RbacWrapper action="phonebook:view">
      <PhonebookPage />
      <Drawer
        size={drawerPercentage}
        onClose={() => {
          delete search.phonebookentry;
          navigate({ search: queryString.stringify(search) });
        }}
        open={phonebookentry}
      >
        <PhonebookFormContainer />
      </Drawer>
    </RbacWrapper>
  );
}

export default connect(null, mapDispatchToProps)(PhonebookContainer);
