import { useMutation, useQuery } from "@apollo/client/react";
import { Form } from "antd";
import queryString from "query-string";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { useLocation, useNavigate } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import { DELETE_VENDOR, INSERT_NEW_VENDOR, QUERY_VENDOR_BY_ID, UPDATE_VENDOR } from "../../graphql/vendors.queries";
import { selectBodyshop } from "../../redux/user/user.selectors";
import AlertComponent from "../alert/alert.component";
import LoadingSpinner from "../loading-spinner/loading-spinner.component";
import VendorsFormComponent from "./vendors-form.component";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

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

function VendorsFormContainer({ refetch, bodyshop }) {
  const history = useNavigate();
  const search = queryString.parse(useLocation().search);
  const { selectedvendor } = search;
  const [formLoading, setFormLoading] = useState(false);
  const [form] = Form.useForm();
  const { t } = useTranslation();
  const { loading, error, data } = useQuery(QUERY_VENDOR_BY_ID, {
    variables: { id: selectedvendor },
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only",
    skip: !selectedvendor || selectedvendor === "new"
  });
  const notification = useNotification();

  const [updateVendor] = useMutation(UPDATE_VENDOR);
  const [insertvendor] = useMutation(INSERT_NEW_VENDOR);
  const [deleteVendor] = useMutation(DELETE_VENDOR);

  const handleDelete = async () => {
    setFormLoading(true);
    const result = await deleteVendor({
      variables: { id: selectedvendor },
      refetchQueries: ["QUERY_ALL_VENDORS"]
    });
    console.log(result);
    if (result.errors) {
      notification.error({
        title: t("vendors.errors.deleting")
      });
    } else {
      notification.success({
        title: t("vendors.successes.deleted")
      });
      delete search.selectedvendor;
      history({ search: queryString.stringify(search) });
      if (refetch)
        refetch().then(() => {
          form.resetFields();
        });
    }

    setFormLoading(false);
  };

  const handleFinish = async (values) => {
    setFormLoading(true);
    if (selectedvendor && selectedvendor !== "new") {
      //It's a vendor to update.
      const result = await updateVendor({
        variables: { id: selectedvendor, vendor: values },
        refetchQueries: ["QUERY_ALL_VENDORS", "QUERY_VENDOR_BY_ID"]
      });

      if (!result.errors) {
        notification.success({
          title: t("vendors.successes.saved")
        });

        if (refetch) await refetch();
        form.setFieldsValue(data.vendors_by_pk);
        form.resetFields();

        setFormLoading(false);
      } else {
        notification.error({
          title: t("vendors.errors.saving")
        });
        console.log("error", error);
        setFormLoading(false);
      }
    } else {
      //It's a new vendor to insert.
      const result = await insertvendor({
        variables: { vendorInput: [{ ...values, bodyshopid: bodyshop.id }] },
        refetchQueries: ["QUERY_ALL_VENDORS"]
      });

      if (!result.errors) {
        notification.success({
          title: t("vendors.successes.saved")
        });

        if (refetch) await refetch();
        form.resetFields();
        form.resetFields();
        const updatedSearch = { ...search };
        delete updatedSearch.selectedvendor;
        history({ search: queryString.stringify(updatedSearch) });
        setFormLoading(false);
      } else {
        notification.error({
          title: t("vendors.errors.saving")
        });
        setFormLoading(false);
      }
    }
  };

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

  if (loading) return <LoadingSpinner />;
  if (error) return <AlertComponent title={error.message} type="error" />;

  return (
    <Form
      onFinish={handleFinish}
      form={form}
      layout="vertical"
      autoComplete="new-password"
      initialValues={data ? data.vendors_by_pk : null}
    >
      {selectedvendor ? (
        <VendorsFormComponent
          form={form}
          formLoading={formLoading}
          handleDelete={handleDelete}
          responsibilityCenters={bodyshop.md_responsibility_centers || null}
          selectedvendor={selectedvendor}
        />
      ) : (
        t("vendors.labels.noneselected")
      )}
    </Form>
  );
}

export default connect(mapStateToProps, null)(VendorsFormContainer);
