import { useMutation, useQuery } from "@apollo/client";
import { Form, Skeleton } from "antd";
import React, { useEffect, useState, useCallback } from "react";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { debounce } from "lodash";
import { QUERY_BODYSHOP, UPDATE_SHOP } from "../../../graphql/bodyshop.queries";
import ipcTypes from "../../../ipc.types";
import { setBodyshop } from "../../../redux/user/user.actions";
import { antdNotification as notification } from "../../../util/antdFeedback";
import ErrorResultAtom from "../../atoms/error-result/error-result.atom";
import ShopSettingsFormMolecule from "../../molecules/shop-settings-form/shop-settings-form.molecule";
const { ipcRenderer } = window;
const mapStateToProps = createStructuredSelector({
  //currentUser: selectCurrentUser
});
const mapDispatchToProps = (dispatch) => ({
  //setUserLanguage: language => dispatch(setUserLanguage(language))
  setBodyshop: (shop) => dispatch(setBodyshop(shop))
});

export function ShopSettingsOrganism({ setBodyshop }) {
  const { loading, error, data } = useQuery(QUERY_BODYSHOP);
  const [form] = Form.useForm();
  const [updateBodyshop] = useMutation(UPDATE_SHOP);
  const [saveLoading, setSaveLoading] = useState(false);

  useEffect(() => {
    if (data) form.resetFields();
  }, [form, data]);

  const handleFinish = async ({ ins_rule_set, ...values }) => {
    setSaveLoading(true);
    ipcRenderer.send(ipcTypes.app.toMain.track, {
      event: "UPDATE_SHOP_DETAILS"
    });

    const result = await updateBodyshop({
      variables: { id: data.bodyshops[0].id, shop: values }
    });

    if (!result.errors) {
      notification["success"]({ message: "Settings saved successfully.", key: "shop_settings_save" });
      //  console.log("r", result.data.update_bodyshops.returning[0]);
      setBodyshop(result.data.update_bodyshops.returning[0]);
      form.resetFields();
    } else {
      notification["error"]({
        message: "Error while saving settings " + error
      });
    }
    setSaveLoading(false);
  };

  // Create debounced auto-save function
  const debouncedAutoSave = debounce(function (changed, values) {
    // Only auto-save if data is loaded
    console.log("Changed values:", changed);
    if (
      data &&
      !loading &&
      Object.keys(changed).some((key) => ["mpi_count_quantity", "accepted_ins_co"].includes(key))
    ) {
      if (Object.keys(changed).includes("mpi_count_quantity")) {
        ipcRenderer.send(ipcTypes.app.toMain.track, {
          event: "TOGGLE_COUNT_PART_QUANTITY",
          mpi_count_quantity: changed.mpi_count_quantity
        });
      }
      //Prevent auto save on shop name.
      form
        .validateFields()
        .then((values) => {
          handleFinish(values);
        })
        .catch(() => {
          // Form validation failed, don't save
          setSaveLoading(false);
        });
    }
  }, 250);

  return (
    <div>
      <Form
        form={form}
        layout="vertical"
        autoComplete="new-password"
        onFinish={handleFinish}
        onValuesChange={debouncedAutoSave}
        initialValues={data ? data.bodyshops[0] : null}
      >
        {loading && <Skeleton />}
        {error && <ErrorResultAtom title="Error displaying job data." />}
        <ShopSettingsFormMolecule loading={loading} form={form} saveLoading={saveLoading} />
      </Form>
    </div>
  );
}

export default connect(mapStateToProps, mapDispatchToProps)(ShopSettingsOrganism);
