import { Button, Form, notification, PageHeader } from "antd";
import React, { useState } from "react";
import { useMutation } from "@apollo/client";
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", {
          error: JSON.stringify(result.errors),
        }),
      });
      setLoading(false);
      return;
    }

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

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

  return (
    <>
      <PageHeader
        title={t("menus.header.owners")}
        extra={
          <Button
            type="primary"
            loading={loading}
            onClick={() => form.submit()}
          >
            {t("general.actions.save")}
          </Button>
        }
      />
      <Form
        form={form}
        onFinish={handleFinish}
        autoComplete="off"
        layout="vertical"
        initialValues={owner}
      >
        <OwnerDetailFormComponent loading={loading} form={form} />
      </Form>
    </>
  );
}
export default OwnerDetailFormContainer;
