import React, { Fragment } from "react";
import { useQuery, useMutation } from "@apollo/client";
import client from "../../apollo/apolloClient";
import {
  GET_SMS_MANAGER,
  UPDATE_TEMPLATE,
  DELETE_TEMPLATE,
  TRIGGER_EDIT,
} from "../../apollo/queries";
import { CREATE_TEMPLATE } from "../../apollo/queries";
import { getOperationName } from "apollo-utilities";
import {
  myManager,
  templateCreate,
  templateCreateVariables,
  templateUpdate,
  templateDelete,
  templateUpdateVariables,
  TemplateUpsertInput,
  templateDeleteVariables,
  triggerListEditToTemplateVariables,
  triggerListEditToTemplate,
  TriggerListEditToTemplateInput,
} from "../../types/api";
import { queryDataFormater, toast } from "@janda-com/front";
import SmsTemplateSetting, { IChainProp } from "./SmsTemplateSetting";
import { ISmsConfig } from "../../app";
import { lang as LANG } from "../../lang/langFn";

export interface ITemplateSettingWrapProp extends IChainProp {}
interface IProps extends IChainProp {
  config: ISmsConfig;
}

export type TController = {
  updateFn: (
    param: templateUpdateVariables,
    triggerParam?: TriggerListEditToTemplateInput | undefined
  ) => Promise<boolean>;
  deleteFn: (param: templateDeleteVariables) => Promise<boolean>;
  createFn: (
    param: TemplateUpsertInput,
    triggerParam?: TriggerListEditToTemplateInput | undefined
  ) => Promise<boolean>;
};

const SmsTemplateSettingWrap: React.FC<IProps> = ({ config, ...props }) => {
  const { data, loading } = useQuery<myManager>(GET_SMS_MANAGER, {
    client,
    onError: (e) => {
      console.error(e);
    },
  });

  const manager = queryDataFormater(data, "MyManager", "data", false) || false;

  const refetchQueries = [getOperationName(GET_SMS_MANAGER) || ""];

  const [triggerEditMu, { loading: triggerEditLoading }] = useMutation<
    triggerListEditToTemplate,
    triggerListEditToTemplateVariables
  >(TRIGGER_EDIT, {
    client,
    refetchQueries,
  });

  const [createMu, { loading: createLoading }] = useMutation<
    templateCreate,
    templateCreateVariables
  >(CREATE_TEMPLATE, {
    client,
  });

  const [updateMu, { loading: updateLoading }] = useMutation<
    templateUpdate,
    templateUpdateVariables
  >(UPDATE_TEMPLATE, {
    client,
  });

  const [deleteMu, { loading: deleteLoading }] = useMutation<
    templateDelete,
    templateDeleteVariables
  >(DELETE_TEMPLATE, {
    client,
    refetchQueries,
  });

  if (loading) return <div />;
  if (!manager) {
    throw Error("Can Not Find Manager");
  }

  const totalLoading =
    deleteLoading || updateLoading || createLoading || triggerEditLoading;

  const erorrFn = () => {
    toast.error(LANG("template_create_fail"));
  };

  const linkUpdater = async (
    templateId?: string,
    param?: TriggerListEditToTemplateInput
  ) => {
    if (!param) return false;
    if (!templateId) {
      erorrFn();
      return false;
    }

    const result = await triggerEditMu({
      variables: {
        input: param,
        templateId,
      },
    });

    const isOk = result.data?.TriggerListEditToTemplate.ok;

    if (isOk) {
      toast.success(LANG("template_update_completed"));
    } else {
      erorrFn();
      return false;
    }

    return isOk || false;
  };

  const createFn = async (
    param: TemplateUpsertInput,
    triggerParam?: TriggerListEditToTemplateInput
  ) => {
    try {
      return await createMu({
        variables: {
          input: param,
        },
      }).then((result) => {
        const templateId = result?.data?.TemplateCreate.data?._id;
        return linkUpdater(templateId, triggerParam);
      });
    } catch (e) {
      erorrFn();
      console.error(e);
      return false;
    }
  };

  const updateFn = async (
    param: templateUpdateVariables,
    triggerParam?: TriggerListEditToTemplateInput
  ) => {
    try {
      return await updateMu({
        variables: param,
      }).then(() => {
        const { templateId } = param;
        return linkUpdater(templateId, triggerParam);
      });
    } catch (e) {
      erorrFn();
      console.error(e);
      return false;
    }
  };

  const deleteFn = async (
    param: templateDeleteVariables,
    removeIds?: string[]
  ) => {
    const { templateId } = param;

    try {
      return await triggerEditMu({
        variables: {
          input: {
            removeTriggerIds: removeIds,
          },
          templateId,
        },
      }).then(async (result) => {
        const isOk = result?.data?.TriggerListEditToTemplate.ok;

        if (!isOk) {
          erorrFn();
          return false;
        }

        const deleteResult = await deleteMu({
          variables: param,
        });

        const finalOk = deleteResult.data?.TemplateDelete.ok;

        if (!finalOk) erorrFn();

        return finalOk || false;
      });
    } catch (e) {
      erorrFn();
      console.error(e);
      return false;
    }
  };

  const controller: TController = {
    updateFn,
    deleteFn,
    createFn,
  };

  return (
    <Fragment>
      {loading || (
        <SmsTemplateSetting
          controller={controller}
          totalLoading={totalLoading}
          config={config}
          manager={manager}
          {...props}
        />
      )}
    </Fragment>
  );
};

export default SmsTemplateSettingWrap;
0;
