import React from "react";
import { useQuery } from "react-apollo";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { QUERY_SHOP_ID } from "../../graphql/bodyshop.queries";
import { GET_DOCUMENTS_BY_JOB } from "../../graphql/documents.queries";
import { selectCurrentUser } from "../../redux/user/user.selectors";
import AlertComponent from "../alert/alert.component";
import LoadingSpinner from "../loading-spinner/loading-spinner.component";
import JobDocuments from "./jobs-documents.component";

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

export default connect(
  mapStateToProps,
  null
)(function JobsDocumentsContainer({ jobId, currentUser }) {
  const { loading, error, data } = useQuery(GET_DOCUMENTS_BY_JOB, {
    variables: { jobId: jobId },
    fetchPolicy: "network-only"
  });

  const shopData = useQuery(QUERY_SHOP_ID, {
    fetchPolicy: "network-only"
  });

  if (loading || shopData.loading) return <LoadingSpinner />;
  if (error || shopData.error)
    return (
      <AlertComponent
        type="error"
        message={error.message || shopData.error.message}
      />
    );

  return (
    <JobDocuments
      data={data.documents}
      jobId={jobId}
      currentUser={currentUser}
      shopId={
        shopData.data.bodyshops[0].id ? shopData.data.bodyshops[0].id : "error"
      }
    />
  );
});
