import { Form, notification } from "antd";
import React from "react";
import { useMutation, useQuery } from "react-apollo";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import {
  DELETE_VENDOR,
  INSERT_NEW_VENDOR,
  UPDATE_VENDOR,
  QUERY_VENDOR_BY_ID
} from "../../graphql/vendors.queries";
import { selectBodyshop } from "../../redux/user/user.selectors";
import VendorsFormComponent from "./vendors-form.component";
import LoadingSpinner from "../loading-spinner/loading-spinner.component";
import AlertComponent from "../alert/alert.component";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop
});

function VendorsFormContainer({ vendorId, refetch, bodyshop }) {
  const [form] = Form.useForm();
  const { t } = useTranslation();
  const { loading, error, data } = useQuery(QUERY_VENDOR_BY_ID, {
    variables: { id: vendorId },
    fetchPolicy: "network-only",
    skip: !vendorId
  });
  const [updateVendor] = useMutation(UPDATE_VENDOR);
  const [insertvendor] = useMutation(INSERT_NEW_VENDOR);
  const [deleteVendor] = useMutation(DELETE_VENDOR);
  const handleDelete = () => {
    deleteVendor({ variables: { id: vendorId } })
      .then(r => {
        notification["success"]({
          message: t("vendors.successes.deleted")
        });
        //TODO Better way to reset the field decorators?
        if (refetch) refetch().then(r => form.resetFields());
      })
      .catch(error => {
        notification["error"]({
          message: t("vendors.errors.deleting")
        });
      });
  };

  const handleFinish = values => {
    delete values.keys;
    if (vendorId) {
      //It's a vendor to update.
      updateVendor({
        variables: { id: vendorId, vendor: values }
      })
        .then(r => {
          notification["success"]({
            message: t("vendors.successes.saved")
          });
          //TODO Better way to reset the field decorators?
          if (refetch) refetch().then(r => form.resetFields());
        })
        .catch(error => {
          notification["error"]({
            message: t("vendors.errors.saving")
          });
        });
    } else {
      //It's a new vendor to insert.
      insertvendor({
        variables: { vendorInput: [{ ...values, bodyshopid: bodyshop.id }] }
      })
        .then(r => {
          notification["success"]({
            message: t("vendors.successes.saved")
          });
          //TODO Better way to reset the field decorators?
          if (refetch) refetch().then(r => form.resetFields());
        })
        .catch(error => {
          notification["error"]({
            message: t("vendors.errors.saving")
          });
        });
    }
  };

  if (loading) return <LoadingSpinner />;
  if (error) return <AlertComponent message={error.message} type="error" />;
  return (
    <Form onFinish={handleFinish} form={form} autoComplete="new-password">
      {data ? (
        <VendorsFormComponent
          form={form}
          vendor={data ? data.vendors_by_pk : null}
          handleDelete={handleDelete}
        />
      ) : (
        t("vendors.labels.noneselected")
      )}
    </Form>
  );
}
export default connect(mapStateToProps, null)(VendorsFormContainer);
