import { Form, notification } from "antd";
import React, { useState } from "react";
import { useMutation } from "@apollo/react-hooks";
import { useTranslation } from "react-i18next";
import { UPDATE_OWNER } from "../../graphql/owners.queries";
import OwnerDetailFormComponent from "./owner-detail-form.component";

function OwnerDetailFormContainer({ owner, refetch }) {
  const { t } = useTranslation();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [updateOwner] = useMutation(UPDATE_OWNER);

  const handleFinish = async (values) => {
    setLoading(true);
    const result = await updateOwner({
      variables: { ownerId: owner.id, owner: values },
    });

    if (!!result.errors) {
      notification["error"]({
        message: t("owners.errors.saving", {
          message: JSON.stringify(result.errors),
        }),
      });
      return;
    }

    notification["success"]({
      message: t("owners.successes.save"),
    });

    if (refetch) await refetch();
    form.resetFields();
    form.resetFields();
    setLoading(false);
  };

  return (
    <Form
      form={form}
      onFinish={handleFinish}
      autoComplete="off"
      layout="vertical"
      initialValues={owner}
    >
      <OwnerDetailFormComponent loading={loading} form={form} />
    </Form>
  );
}
export default OwnerDetailFormContainer;
