import { DownOutlined } from "@ant-design/icons";
import { useMutation } from "@apollo/client";
import { Dropdown, Menu } from "antd";
import queryString from "query-string";
import React from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { useHistory, useLocation } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import { logImEXEvent } from "../../firebase/firebase.utils";
import {
  INSERT_TEMPLATE,
  QUERY_TEMPLATES_BY_NAME_FOR_DUPE,
} from "../../graphql/templates.queries";
import { selectBodyshop } from "../../redux/user/user.selectors";
import client from "../../utils/GraphQLClient";
import { TemplateList } from "../../utils/TemplateConstants";

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

export default connect(mapStateToProps, null)(ShopTemplateAddComponent);

export function ShopTemplateAddComponent({
  bodyshop,
  shopTemplateList,
  refetch,
}) {
  const { t } = useTranslation();
  const search = queryString.parse(useLocation().search);
  const history = useHistory();
  const [insertTemplate] = useMutation(INSERT_TEMPLATE);

  const shopTemplateKeys = shopTemplateList.map((template) => template.name);
  const availableTemplateKeys = Object.keys(TemplateList()).filter(
    (tkey) => !shopTemplateKeys.includes(tkey)
  );

  const handleAdd = async (item) => {
    logImEXEvent("shop_template_add");

    const defaultTemplateData = await client.query({
      query: QUERY_TEMPLATES_BY_NAME_FOR_DUPE,
      variables: { name: item.key },
    });

    const template = defaultTemplateData.data.templates.filter(
      (t) => t.bodyshopid === null
    )[0];

    const result = await insertTemplate({
      variables: {
        template: {
          name: item.key,
          bodyshopid: bodyshop.id,
          jsontemplate: template && template.jsontemplate,
          html: template && template.html,
          query: template && template.query,
        },
      },
    });

    const returningId = result.data.insert_templates.returning[0].id;
    search.customTemplateId = returningId;
    history.push({ search: queryString.stringify(search) });
    if (!!refetch) refetch();
  };
  const TemplateListGenerated = TemplateList();
  const menu = (
    <Menu onClick={handleAdd}>
      {availableTemplateKeys.length > 0 ? (
        availableTemplateKeys.map((tkey) => (
          <Menu.Item key={tkey}>{TemplateListGenerated[tkey].title}</Menu.Item>
        ))
      ) : (
        <div>{t("bodyshop.labels.notemplatesavailable")}</div>
      )}
    </Menu>
  );

  return (
    <Dropdown overlay={menu}>
      <span>
        {t("bodyshop.actions.addtemplate")} <DownOutlined />
      </span>
    </Dropdown>
  );
}
