import { Tabs } from "antd";
import queryString from "query-string";
import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { useLocation, useNavigate } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import RbacWrapper from "../../components/rbac-wrapper/rbac-wrapper.component";
import ShopVendorPageComponent from "../shop-vendor/shop-vendor.page.component";
import { setBreadcrumbs, setSelectedHeader } from "../../redux/application/application.actions";
import InstanceRenderManager from "../../utils/instanceRenderMgr";
import PartsShopInfoContainer from "../../components/parts-shop-info/parts-shop-info.container";

const mapStateToProps = createStructuredSelector({});

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

export function PartsSettingsPage({ setSelectedHeader, setBreadcrumbs }) {
  const { t } = useTranslation();
  const history = useNavigate();
  const search = queryString.parse(useLocation().search);

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

  useEffect(() => {
    if (!search.tab) history({ search: "?tab=shop" });
  }, [history, search]);

  const items = [
    {
      key: "shop",
      label: t("bodyshop.labels.parts_shop_management"),
      children: (
        <RbacWrapper action="shop:config">
          <PartsShopInfoContainer />
        </RbacWrapper>
      )
    },
    {
      key: "vendors",
      label: t("bodyshop.labels.parts_vendor_management"),
      children: (
        <RbacWrapper action="shop:vendors">
          <ShopVendorPageComponent />
        </RbacWrapper>
      )
    }
  ];

  return <Tabs activeKey={search.tab} onChange={(key) => history({ search: `?tab=${key}` })} items={items} />;
}

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