import React from "react";
import { useQuery, useMutation } from "react-apollo";
import {
  QUERY_ALL_ASSOCIATIONS,
  UPDATE_ASSOCIATION
} from "../../graphql/associations.queries";
import AlertComponent from "../alert/alert.component";
import ProfileShopsComponent from "./profile-shops.component";

export default function ProfileShopsContainer() {
  const { loading, error, data, refetch } = useQuery(QUERY_ALL_ASSOCIATIONS);
  const [updateAssocation] = useMutation(UPDATE_ASSOCIATION);

  const updateActiveShop = activeShopId => {
    data.associations.forEach(record => {
      updateAssocation({
        variables: {
          assocId: record.id,
          assocActive: record.id === activeShopId ? true : false
        }
      });
    });
    refetch();
  };

  if (error) return <AlertComponent type="error" message={error.message} />;
  return (
    <ProfileShopsComponent
      loading={loading}
      data={data ? data.associations : null}
      updateActiveShop={updateActiveShop}
    />
  );
}
