import { Button, Space } from "antd";
import axios from "axios";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectBodyshop, selectCurrentUser } from "../../redux/user/user.selectors";
import { useTreatmentsWithConfig } from "@splitsoftware/splitio-react";

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

export function DmsCdkMakesRefetch({ currentUser, bodyshop }) {
  const [loading, setLoading] = useState(false);
  const { t } = useTranslation();
  const {
    treatments: { Fortellis }
  } = useTreatmentsWithConfig({
    attributes: {},
    names: ["Fortellis"],
    splitKey: bodyshop.imexshopid
  });

  if (!currentUser.email.includes("@imex.")) return null;

  const handleRefetch = async () => {
    try {
      setLoading(true);
      await axios.post(`cdk${Fortellis.treatment === "on" ? "/fortellis" : ""}/getvehicles`, {
        cdk_dealerid: bodyshop.cdk_dealerid,
        bodyshopid: bodyshop.id
      });
    } catch (error) {
      console.error(error);
    }

    setLoading(false);
  };

  const handleGetCOA = async () => {
    try {
      setLoading(true);
      await axios.post(`cdk/fortellis/getCOA`, {
        cdk_dealerid: bodyshop.cdk_dealerid,
        bodyshopid: bodyshop.id
      });
    } catch (error) {
      console.error(error);
    }

    setLoading(false);
  };

  return (
    <Space>
      <Button loading={loading} onClick={handleRefetch}>
        {t("jobs.actions.dms.refetchmakesmodels")}
      </Button>
      <Button loading={loading} onClick={handleGetCOA}>
        Get COA
      </Button>
    </Space>
  );
}
