import React, { 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 queryString from "query-string";
import { useHistory, useLocation } from "react-router-dom";
import PhonebookFormContainer from "../../components/phonebook-form/phonebook-form.container";
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");
    setSelectedHeader("phonebook");
    setBreadcrumbs([
      {
        link: "/manage/phonebook",
        label: t("titles.bc.phonebook"),
      },
    ]);
  }, [setBreadcrumbs, t, setSelectedHeader]);
  const search = queryString.parse(useLocation().search);
  const { phonebookentry } = search;
  const history = useHistory();

  const selectedBreakpoint = Object.entries(Grid.useBreakpoint())
    .filter((screen) => !!screen[1])
    .slice(-1)[0];

  const bpoints = {
    xs: "100%",
    sm: "100%",
    md: "100%",
    lg: "50%",
    xl: "50%",
    xxl: "45%",
  };
  const drawerPercentage = selectedBreakpoint
    ? bpoints[selectedBreakpoint[0]]
    : "100%";

  return (
    <RbacWrapper action="phonebook:view">
      <PhonebookPage />
      <Drawer
        width={drawerPercentage}
        onClose={() => {
          delete search.phonebookentry;
          history.push({ search: queryString.stringify(search) });
        }}
        visible={phonebookentry}
      >
        <PhonebookFormContainer />
      </Drawer>
    </RbacWrapper>
  );
}
export default connect(null, mapDispatchToProps)(PhonebookContainer);
