import React from "react";
import TriggerSetting from "./TriggerSetting";
import { ISmsConfig } from "../../../app";
import { useMutation } from "@apollo/client";
import {
  TRIGGER_CREATE,
  UPDATE_TRIGGER,
  GET_SMS_MANAGER,
} from "../../../apollo/queries";
import client from "../../../apollo/apolloClient";
import {
  triggerCreate,
  triggerCreateVariables,
  triggerUpdate,
  triggerUpdateVariables,
  TriggerUpsertInput,
} from "../../../types/api";
import { IManager } from "../../../types/interface";
import { IChainProp as ITriggerChain } from "./TriggerSetting";
import { onCompletedMessage } from "@janda-com/front";
import { lang } from "../../../lang/langFn";
import { getOperationName } from "apollo-utilities";
import { TtagsOp } from "./TriggerModal";

export interface IChainProp {
  tagsOp?: TtagsOp;
}

interface Iprop extends IChainProp, ITriggerChain {
  config: ISmsConfig;
  manager: IManager;
}

const TriggerSettingWrap: React.FC<Iprop> = ({
  config,
  manager,
  modalHook,
  tagsOp,
  ...props
}) => {
  const { triggers,senders } = manager;

  const [createMu, { loading: createLoding }] = useMutation<
    triggerCreate,
    triggerCreateVariables
  >(TRIGGER_CREATE, {
    client,
    refetchQueries: [getOperationName(GET_SMS_MANAGER) || ""],
    onCompleted: ({ TriggerCreate }) => {
      onCompletedMessage(
        TriggerCreate,
        lang("trigger_create"),
        "이런 문제가 생겼습니다"
      );
    },
  });

  const [updateMu, { loading: updateLoding }] = useMutation<
    triggerUpdate,
    triggerUpdateVariables
  >(UPDATE_TRIGGER, {
    client,
    refetchQueries: [getOperationName(GET_SMS_MANAGER) || ""],
    onCompleted: ({ TriggerUpdate }) => {
      onCompletedMessage(
        TriggerUpdate,
        lang("trigger_updated"),
        "이런 문제가 생겼습니다"
      );
    },
  });

  const createFn = async (input: TriggerUpsertInput) => {
    return await createMu({
      variables: {
        input,
      },
    });
  };

  const updateFn = async (id: string, input: TriggerUpsertInput) => {
    return await updateMu({
      variables: {
        input,
        triggerId: id,
      },
    });
  };

  const totalLoading = createLoding || updateLoding;

  return (
    <TriggerSetting
      modalHook={modalHook}
      tagsOp={tagsOp || []}
      triggers={triggers}
      totalLoading={totalLoading}
      {...props}
      updateFn={updateFn}
      createFn={createFn}
      config={config}
      senders={senders}
    />
  );
};

export default TriggerSettingWrap;
