import { DownOutlined } from "@ant-design/icons";
import { useMutation } from "@apollo/client/react";
import { Dropdown } from "antd";
import queryString from "query-string";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { useLocation, useNavigate } 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";
import { isFunction } from "lodash";

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 = useNavigate();
  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({ search: queryString.stringify(search) });
    if (refetch && isFunction(refetch)) refetch();
  };
  const TemplateListGenerated = TemplateList();
  const menu = {
    onClick: handleAdd,

    items:
      availableTemplateKeys.length > 0
        ? availableTemplateKeys.map((tkey) => ({
            key: tkey,
            label: TemplateListGenerated[tkey].title
          }))
        : [
            {
              key: "no-templates",
              label: t("bodyshop.labels.notemplatesavailable"),
              disabled: true
            }
          ]
  };

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