import { useMutation, useQuery } from "@apollo/client/react";
import { Form } from "antd";
import { useEffect, useMemo, 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 ShopInfoComponent from "./shop-info.component";
import { FEATURE_CONFIGS, useFormDataPreservation } from "./useFormDataPreservation";

export default function ShopInfoContainer() {
  const [form] = Form.useForm();
  const { t } = useTranslation();
  const [isShopInfoDirty, setIsShopInfoDirty] = useState(false);
  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 combineFeatureConfigs = (...configs) =>
    (configs || [])
      .filter(Boolean)
      .flatMap((cfg) => Object.entries(cfg))
      .reduce((acc, [featureName, fieldPaths]) => {
        if (!Array.isArray(fieldPaths)) return acc;
        acc[featureName] = [...(acc[featureName] ?? []), ...fieldPaths];
        return acc;
      }, {});

  const combinedFeatureConfig = useMemo(
    () => combineFeatureConfigs(FEATURE_CONFIGS.general, FEATURE_CONFIGS.responsibilitycenters),
    []
  );

  // Use form data preservation for all shop-info features
  const { createSubmissionHandler, preserveHiddenFormData } = useFormDataPreservation(
    form,
    data?.bodyshops[0],
    combinedFeatureConfig
  );

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

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

  useEffect(() => {
    if (!data) return;
    form.resetFields();
    // After reset, re-apply hidden field preservation so values aren't wiped
    preserveHiddenFormData();
    setIsShopInfoDirty(false);
  }, [data, form, preserveHiddenFormData]);

  if (error) return <AlertComponent title={error.message} type="error" />;
  if (loading) return <LoadingSpinner />;
  return (
    <Form
      form={form}
      layout="vertical"
      autoComplete="new-password"
      onFinish={handleFinish}
      onValuesChange={() => {
        setIsShopInfoDirty(form.isFieldsTouched());
      }}
      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} onDirtyChange={setIsShopInfoDirty} />
      <ShopInfoComponent form={form} saveLoading={saveLoading} isDirty={isShopInfoDirty} />
    </Form>
  );
}
