import { useQuery } from "@apollo/client/react";
import { Result } from "antd";
import queryString from "query-string";
import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { useLocation } from "react-router-dom";
import { QUERY_BODYSHOP } from "../../graphql/bodyshop.queries";
import { GET_DOCUMENT_BY_PK } from "../../graphql/documents.queries";
import { setBodyshop } from "../../redux/user/user.actions";
import AlertComponent from "../alert/alert.component";
import LoadingSpinner from "../loading-spinner/loading-spinner.component";
import DocumentEditor from "./document-editor.component";
import { DocumentEditorLocalComponent } from "./document-editor-local.component";

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

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

export function DocumentEditorContainer({ setBodyshop }) {
  //Get the image details for the image to be saved.
  //Get the document id from the search string.
  const { documentId, imageUrl, filename, jobid } = queryString.parse(useLocation().search);
  const { t } = useTranslation();
  const {
    loading: loadingShop,
    error: errorShop,
    data: dataShop
  } = useQuery(QUERY_BODYSHOP, {
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only"
  });

  const isLocalMedia = !!dataShop?.bodyshops?.[0]?.uselocalmediaserver;

  const {
    loading: loadingDoc,
    error: errorDoc,
    data: dataDoc
  } = useQuery(GET_DOCUMENT_BY_PK, {
    variables: { documentId },
    skip: !documentId || isLocalMedia,
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only"
  });

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

  if (loadingShop) return <LoadingSpinner />;
  if (errorShop) return <AlertComponent title={errorShop.message} type="error" />;

  if (isLocalMedia) {
    if (imageUrl && filename && jobid) {
      return (
        <div>
          <DocumentEditorLocalComponent imageUrl={imageUrl} filename={filename} jobid={jobid} />
        </div>
      );
    } else {
      return <Result status="404" title={t("general.errors.notfound")} />;
    }
  }

  if (loadingDoc) return <LoadingSpinner />;
  if (errorDoc) return <AlertComponent title={errorDoc.message} type="error" />;

  if (!dataDoc || !dataDoc.documents_by_pk) return <Result status="404" title={t("general.errors.notfound")} />;
  return (
    <div>
      <DocumentEditor document={dataDoc ? dataDoc.documents_by_pk : null} />
    </div>
  );
}
