import { useMutation, useQuery } from "@apollo/client/react";
import { Form } from "antd";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";
import { logImEXEvent } from "../../firebase/firebase.utils";
import { QUERY_BODYSHOP, UPDATE_SHOP } from "../../graphql/bodyshop.queries";
import dayjs from "../../utils/day";
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 PartsShopManagementComponent from "./parts-shop-management.component";

export default function PartsShopInfoContainer() {
  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 notification = useNotification();

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

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

    setSaveLoading(false);
  };

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

  if (error) return <AlertComponent title={error.message} type="error" />;
  if (loading) return <LoadingSpinner />;

  return (
    <Form
      form={form}
      layout="vertical"
      autoComplete="new-password"
      onFinish={handleFinish}
      initialValues={
        data?.bodyshops?.[0]
          ? {
              ...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} />
      <PartsShopManagementComponent form={form} saveLoading={saveLoading} />
    </Form>
  );
}
