import { Button } from "antd";
import { useState } from "react";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { useTranslation } from "react-i18next";
import { useMutation } from "@apollo/client/react";
import { INSERT_NEW_PHONEBOOK } from "../../graphql/phonebook.queries";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop
});
const mapDispatchToProps = () => ({
  //setUserLanguage: language => dispatch(setUserLanguage(language))
});
export default connect(mapStateToProps, mapDispatchToProps)(VendorsPhonebookAdd);

export function VendorsPhonebookAdd({ form, bodyshop, disabled }) {
  const [loading, setLoading] = useState(false);
  const [insertPhonebook] = useMutation(INSERT_NEW_PHONEBOOK);
  const { t } = useTranslation();
  const notification = useNotification();

  const handleAdd = async () => {
    setLoading(true);

    const VendorValues = form.getFieldsValue([
      "name",
      "email",
      "phone",
      "street1",
      "street2",
      "city",
      "state",
      "zip",
      "country"
    ]);

    const result = await insertPhonebook({
      variables: {
        phonebook_entry: [
          {
            //The phonebook obj,
            bodyshopid: bodyshop.id,
            company: VendorValues.name,
            category: t("phonebook.labels.vendorcategory"),
            address1: VendorValues.street1,
            address2: VendorValues.street2,
            city: VendorValues.city,
            state: VendorValues.state,
            zip: VendorValues.zip,
            country: VendorValues.country,
            phone1: VendorValues.phone,
            email: VendorValues.email
          }
        ]
      }
    });

    if (result.errors) {
      notification.error({
        title: t("phonebook.errors.adding", {
          error: JSON.stringify(result.errors)
        })
      });
    } else {
      notification.success({
        title: t("phonebook.successes.added")
      });
    }
    setLoading(false);
  };

  return (
    <Button onClick={handleAdd} loading={loading} disabled={disabled}>
      {t("vendors.actions.addtophonebook")}
    </Button>
  );
}
