import { useQuery } from "@apollo/client/react";
import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import AlertComponent from "../../components/alert/alert.component";
import LoadingSpinner from "../../components/loading-spinner/loading-spinner.component";
import { QUERY_BODYSHOP } from "../../graphql/bodyshop.queries";
import { setBodyshop } from "../../redux/user/user.actions";
import SimplifiedPartsPage from "./simplified-parts.page.component";

const mapDispatchToProps = (dispatch) => ({
  setBodyshop: (bs) => dispatch(setBodyshop(bs))
});

function SimplifiedPartsPageContainer({ setBodyshop }) {
  const { loading, error, data } = useQuery(QUERY_BODYSHOP, {
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only"
  });

  const { t } = useTranslation();

  useEffect(() => {
    if (data) {
      setBodyshop(data.bodyshops[0] || { notfound: true });
    }
  }, [data, setBodyshop]);

  if (loading) return <LoadingSpinner message={t("general.labels.loadingshop")} />;
  if (error) return <AlertComponent title={error.message} type="error" />;

  return <SimplifiedPartsPage />;
}

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