import { useTreatmentsWithConfig } from "@splitsoftware/splitio-react";
import { Button, Card, Tabs } from "antd";
import queryString from "query-string";
import { useRef } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { useLocation, useNavigate } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import { useSocket } from "../../contexts/SocketIO/useSocket.js";
import { selectBodyshop } from "../../redux/user/user.selectors";
import InstanceRenderManager from "../../utils/instanceRenderMgr";
import { HasFeatureAccess } from "../feature-wrapper/feature-wrapper.component";
import LockWrapperComponent from "../lock-wrapper/lock-wrapper.component";
import ShopInfoGeneral from "./shop-info.general.component";
import ShopInfoIntakeChecklistComponent from "./shop-info.intake.component";
import ShopInfoLaborRates from "./shop-info.laborrates.component";
import ShopInfoNotificationsAutoadd from "./shop-info.notifications-autoadd.component.jsx";
import ShopInfoOrderStatusComponent from "./shop-info.orderstatus.component";
import ShopInfoPartsScan from "./shop-info.parts-scan";
import ShopInfoRbacComponent from "./shop-info.rbac.component";
import ShopInfoResponsibilityCenterComponent from "./shop-info.responsibilitycenters.component";
import ShopInfoRoGuard from "./shop-info.roguard.component";
import ShopInfoROStatusComponent from "./shop-info.rostatus.component";
import ShopInfoSchedulingComponent from "./shop-info.scheduling.component";
import ShopInfoSectionNavigator from "./shop-info.section-navigator.component.jsx";
import ShopInfoSpeedPrint from "./shop-info.speedprint.component";
import ShopInfoTaskPresets from "./shop-info.task-presets.component";
import ShopInfoIntellipay from "./shop-intellipay-config.component";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop
});
const mapDispatchToProps = () => ({
  //setUserLanguage: language => dispatch(setUserLanguage(language))
});
export default connect(mapStateToProps, mapDispatchToProps)(ShopInfoComponent);

export function ShopInfoComponent({ bodyshop, form, saveLoading, isDirty }) {
  const {
    treatments: { CriticalPartsScanning, Enhanced_Payroll }
  } = useTreatmentsWithConfig({
    attributes: {},
    names: ["CriticalPartsScanning", "Enhanced_Payroll"],
    splitKey: bodyshop.imexshopid
  });
  const { scenarioNotificationsOn } = useSocket();

  const { t } = useTranslation();
  const history = useNavigate();
  const location = useLocation();
  const search = queryString.parse(location.search);
  const tabsRef = useRef(null);

  const tabItems = [
    {
      key: "general",
      label: t("bodyshop.labels.shopinfo"),
      children: <ShopInfoGeneral form={form} />,
      id: "tab-shop-general"
    },
    {
      key: "speedprint",
      label: t("bodyshop.labels.speedprint"),
      children: <ShopInfoSpeedPrint form={form} />,
      id: "tab-shop-speedprint"
    },
    {
      key: "rbac",
      label: t("bodyshop.labels.rbac"),
      children: <ShopInfoRbacComponent form={form} />,
      id: "tab-shop-rbac"
    },
    {
      key: "roStatus",
      label: t("bodyshop.labels.jobstatuses"),
      children: <ShopInfoROStatusComponent form={form} />,
      id: "tab-shop-rostatus"
    },
    {
      key: "scheduling",
      label: t("bodyshop.labels.scheduling"),
      children: <ShopInfoSchedulingComponent form={form} />,
      id: "tab-shop-scheduling"
    },
    {
      key: "orderStatus",
      label: t("bodyshop.labels.orderstatuses"),
      children: <ShopInfoOrderStatusComponent form={form} />,
      id: "tab-shop-orderstatus"
    },
    {
      key: "responsibilityCenters",
      label: t("bodyshop.labels.responsibilitycenters.title"),
      children: <ShopInfoResponsibilityCenterComponent form={form} />,
      id: "tab-shop-responsibilitycenters"
    },

    {
      key: "checklists",
      label: <LockWrapperComponent featureName="checklist">{t("bodyshop.labels.checklists")}</LockWrapperComponent>,
      children: <ShopInfoIntakeChecklistComponent form={form} />,
      disabled: !HasFeatureAccess({ bodyshop, featureName: "checklist" }),
      id: "tab-shop-checklists"
    },
    {
      key: "laborrates",
      label: t("bodyshop.labels.laborrates"),
      children: <ShopInfoLaborRates form={form} />,
      id: "tab-shop-laborrates"
    },
    ...(CriticalPartsScanning.treatment === "on"
      ? [
          {
            key: "partsscan",
            label: t("bodyshop.labels.partsscan"),
            children: <ShopInfoPartsScan form={form} />,
            id: "tab-shop-partsscan"
          }
        ]
      : []),
    ...(Enhanced_Payroll.treatment === "on"
      ? [
          {
            key: "task-presets",
            label: t("bodyshop.labels.task-presets"),
            children: <ShopInfoTaskPresets form={form} />,
            id: "tab-shop-task-presets"
          }
        ]
      : []),
    ...(HasFeatureAccess({ featureName: "roguard", bodyshop })
      ? [
          {
            key: "roguard",
            label: t("bodyshop.labels.roguard.title"),
            children: <ShopInfoRoGuard form={form} />,
            id: "tab-shop-roguard"
          }
        ]
      : []),

    {
      key: "intellipay",
      label: InstanceRenderManager({
        rome: t("bodyshop.labels.romepay"),
        imex: t("bodyshop.labels.imexpay")
      }),
      children: <ShopInfoIntellipay form={form} />
    },
    ...(scenarioNotificationsOn
      ? [
          {
            key: "notifications_autoadd",
            label: t("bodyshop.labels.notifications.followers"),
            children: <ShopInfoNotificationsAutoadd form={form} bodyshop={bodyshop} />
          }
        ]
      : [])
  ];
  const activeTabKey = search.subtab || tabItems[0]?.key;

  return (
    <Card
      title={<ShopInfoSectionNavigator tabsRef={tabsRef} activeTabKey={activeTabKey} />}
      extra={
        <Button
          type="primary"
          disabled={!isDirty || saveLoading}
          loading={saveLoading}
          onClick={() => form.submit()}
          id="shop-info-save-button"
          style={{ minWidth: 210 }}
        >
          {t("bodyshop.actions.save_shop_information")}
        </Button>
      }
    >
      <div ref={tabsRef}>
        <Tabs
          activeKey={activeTabKey}
          onChange={(key) =>
            history({
              search: `?tab=${search.tab}&subtab=${key}`
            })
          }
          items={tabItems}
        />
      </div>
    </Card>
  );
}
