import { useMutation } from "@apollo/client";
import React, { useState } from "react";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { Button, Form, Input, notification, Popover, Space } from "antd";
import { useTranslation } from "react-i18next";
import { UPDATE_SHOP } from "../../graphql/bodyshop.queries";
import { logImEXEvent } from "../../firebase/firebase.utils";

const mapStateToProps = createStructuredSelector({
  //currentUser: selectCurrentUser
  bodyshop: selectBodyshop,
});
const mapDispatchToProps = (dispatch) => ({
  //setUserLanguage: language => dispatch(setUserLanguage(language))
});

export function ProductionListSaveConfigButton({
  columns,
  bodyshop,
  tableState,
}) {
  const [updateShop] = useMutation(UPDATE_SHOP);
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  const [form] = Form.useForm();

  const { t } = useTranslation();

  const handleSaveConfig = async (values) => {
    logImEXEvent("production_save_config");
    setLoading(true);
    const result = await updateShop({
      variables: {
        id: bodyshop.id,
        shop: {
          production_config: [
            ...bodyshop.production_config.filter((b) => b.name !== values.name),
            //Assign it to the name
            {
              name: values.name,
              columns: {
                columnKeys: columns.map((i) => {
                  return { key: i.key, width: i.width };
                }),
                tableState,
              },
            },
          ],
        },
      },
    });
    if (!!!result.errors) {
      notification["success"]({ message: t("bodyshop.successes.save") });
    } else {
      notification["error"]({
        message: t("bodyshop.errors.saving", {
          error: JSON.stringify(result.errors),
        }),
      });
    }
    form.resetFields();
    setVisible(false);
    setLoading(false);
  };
  const popMenu = (
    <div>
      <Form layout="vertical" form={form} onFinish={handleSaveConfig}>
        <Form.Item
          label={t("production.labels.viewname")}
          name="name"
          rules={[{ required: true }]}
        >
          <Input />
        </Form.Item>

        <Space wrap>
          <Button type="danger" onClick={() => form.submit()} loading={loading}>
            {t("general.actions.save")}
          </Button>
          <Button onClick={() => setVisible(false)}>
            {t("general.actions.close")}
          </Button>
        </Space>
      </Form>
    </div>
  );

  return (
    <Popover visible={visible} content={popMenu}>
      <Button loading={loading} onClick={() => setVisible(true)}>
        {t("production.actions.saveconfig")}
      </Button>
    </Popover>
  );
}
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(ProductionListSaveConfigButton);
