import { notification } from "antd";
import React, { useEffect } from "react";
import { useQuery } from "react-apollo";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import LoadingSpinner from "../../components/loading-spinner/loading-spinner.component";
import { QUERY_BODYSHOP } from "../../graphql/bodyshop.queries";
import { setBodyshop } from "../../redux/user/user.actions";
import {
  selectBodyshop,
  selectCurrentUser
} from "../../redux/user/user.selectors";
import ManagePage from "./manage.page.component";

const mapStateToProps = createStructuredSelector({
  currentUser: selectCurrentUser,
  bodyshop: selectBodyshop
});

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

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(function ManagePageContainer({ match, setBodyshop, bodyshop }) {
  const { error, data } = useQuery(QUERY_BODYSHOP, {
    fetchPolicy: "network-only"
  });
  const { t } = useTranslation();
  if (error) {
    notification["error"]({ message: t("bodyshop.errors.loading") });
  }

  useEffect(() => {
    if (data) setBodyshop(data.bodyshops[0]);
    return () => {};
  }, [data, setBodyshop]);

  if (!bodyshop)
    return <LoadingSpinner message={t("general.labels.loadingshop")} />;
  return <ManagePage match={match} />;
});
