import React, { useEffect, useState } from "react";
import ShopInfoComponent from "./shop-info.component";
import { Form, notification } from "antd";
import { useQuery, useMutation } from "@apollo/client";
import { QUERY_BODYSHOP, UPDATE_SHOP } from "../../graphql/bodyshop.queries";
import LoadingSpinner from "../loading-spinner/loading-spinner.component";
import AlertComponent from "../alert/alert.component";
import { useTranslation } from "react-i18next";
import { logImEXEvent } from "../../firebase/firebase.utils";
import FormsFieldChanged from "../form-fields-changed-alert/form-fields-changed-alert.component";
import moment from "moment";
export default function ShopInfoContainer() {
  const [form] = Form.useForm();
  const { t } = useTranslation();
  const [saveLoading, setSaveLoading] = useState(false);
  const [updateBodyshop] = useMutation(UPDATE_SHOP);
  const { loading, error, data, refetch } = useQuery(QUERY_BODYSHOP, {
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only",
  });

  const handleFinish = (values) => {
    setSaveLoading(true);
    logImEXEvent("shop_update");

    updateBodyshop({
      variables: { id: data.bodyshops[0].id, shop: values },
    })
      .then((r) => {
        notification["success"]({ message: t("bodyshop.successes.save") });
        refetch().then((_) => form.resetFields());
      })
      .catch((error) => {
        notification["error"]({
          message: t("bodyshop.errors.saving", { message: error }),
        });
      });
    setSaveLoading(false);
  };

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

  if (error) return <AlertComponent message={error.message} type="error" />;
  if (loading) return <LoadingSpinner />;
  return (
    <Form
      form={form}
      layout="vertical"
      autoComplete="new-password"
      onFinish={handleFinish}
      initialValues={
        data
          ? {
              ...data.bodyshops[0],
              schedule_start_time: moment(
                data.bodyshops[0].schedule_start_time
              ),
              schedule_end_time: moment(data.bodyshops[0].schedule_end_time),
            }
          : null
      }
    >
      <FormsFieldChanged form={form} />
      <ShopInfoComponent form={form} saveLoading={saveLoading} />
    </Form>
  );
}
