import { Button, Form, notification, Popconfirm } from "antd";
import { PageHeader } from "@ant-design/pro-layout";

import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useMutation } from "@apollo/client";
import { useTranslation } from "react-i18next";
import { DELETE_OWNER, 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 history = useNavigate();
  const [loading, setLoading] = useState(false);
  const [updateOwner] = useMutation(UPDATE_OWNER);
  const [deleteOwner] = useMutation(DELETE_OWNER);

  const handleDelete = async () => {
    setLoading(true);
    const result = await deleteOwner({
      variables: { id: owner.id }
    });
    console.log(result);
    if (result.errors) {
      notification["error"]({
        message: t("owners.errors.deleting", {
          error: JSON.stringify(result.errors)
        })
      });
      setLoading(false);
    } else {
      notification["success"]({
        message: t("owners.successes.delete")
      });
      setLoading(false);
      history(`/manage/owners`);
    }
  };

  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={[
          <Popconfirm
            trigger="click"
            onConfirm={handleDelete}
            disabled={owner.jobs.length !== 0}
            title={t("owners.labels.deleteconfirm")}
          >
            <Button type="primary" danger loading={loading} disabled={owner.jobs.length !== 0}>
              {t("general.actions.delete")}
            </Button>
          </Popconfirm>,
          <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;
