import { useMutation, useQuery } from "@apollo/client";
import { Form, notification, Skeleton } from "antd";
import React, { useEffect, useState } from "react";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { QUERY_BODYSHOP, UPDATE_SHOP } from "../../../graphql/bodyshop.queries";
import ipcTypes from "../../../ipc.types";
import { setBodyshop } from "../../../redux/user/user.actions";
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 (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." });
      //  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);
  };

  return (
    <div>
      <Form
        form={form}
        layout="vertical"
        autoComplete="new-password"
        onFinish={handleFinish}
        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);
