import { useMutation, useQuery } from "@apollo/client";
import { Form, notification } from "antd";
import dayjs from "../../utils/day";
import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { logImEXEvent } from "../../firebase/firebase.utils";
import { QUERY_BODYSHOP, UPDATE_SHOP } from "../../graphql/bodyshop.queries";
import AlertComponent from "../alert/alert.component";
import FormsFieldChanged from "../form-fields-changed-alert/form-fields-changed-alert.component";
import LoadingSpinner from "../loading-spinner/loading-spinner.component";
import ShopInfoComponent from "./shop-info.component";

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].accountingconfig.ClosingPeriod
            ? {
                ...data.bodyshops[0],
                accountingconfig: {
                  ...data.bodyshops[0].accountingconfig,
                  ClosingPeriod: [
                    dayjs(data.bodyshops[0].accountingconfig.ClosingPeriod[0]),
                    dayjs(data.bodyshops[0].accountingconfig.ClosingPeriod[1])
                  ]
                },
                schedule_start_time: dayjs(data.bodyshops[0].schedule_start_time),
                schedule_end_time: dayjs(data.bodyshops[0].schedule_end_time)
              }
            : {
                ...data.bodyshops[0],
                schedule_start_time: dayjs(data.bodyshops[0].schedule_start_time),
                schedule_end_time: dayjs(data.bodyshops[0].schedule_end_time)
              }
          : null
      }
    >
      <FormsFieldChanged form={form} />
      <ShopInfoComponent form={form} saveLoading={saveLoading} />
    </Form>
  );
}
