import React, { Dispatch } from "react";
import { ITrigger } from "../../../types/interface";
import { lang as LANG } from "../../../lang/langFn";
import {
  JDalign,
  JDbutton,
  JDpreloader,
  IUseModal,
  JDtypho,
  JDbadge,
  JDcard,
} from "@janda-com/front";
import { ISmsConfig } from "../../../app";
import TriggerModal, {
  IChainProp as IModalChainProp,
  ITriggerModalInfo,
} from "./TriggerModal";
import {
  TriggerUpsertInput,
  triggerUpdate,
  triggerCreate,
  myManager_MyManager_data_senders,
} from "../../../types/api";
import { ExecutionResult } from "graphql";
import { LabelValue } from "../../../atom/LabelValue";

export interface IChainProp extends IModalChainProp {
  modalHook: IUseModal<ITriggerModalInfo>;
}

export type TUpdateFn = (
  id: string,
  input: TriggerUpsertInput
) => Promise<ExecutionResult<triggerUpdate>>;

export type TCreateFn = (
  input: TriggerUpsertInput
) => Promise<ExecutionResult<triggerCreate>>;
//다음 버전부터 라이브러리에 있음
export type ISet<T> = Dispatch<React.SetStateAction<T>>;

interface Iprops extends IChainProp {
  config: ISmsConfig;
  triggers: ITrigger[];
  totalLoading?: boolean;
  updateFn: TUpdateFn;
  createFn: TCreateFn;
  senders: myManager_MyManager_data_senders[];
}

const TriggerSetting: React.FC<Iprops> = ({
  triggers,
  totalLoading,
  templatesOp,
  autoSendCases,
  tagsOp,
  createFn,
  updateFn,
  modalHook,
  senders
}) => {
  const validater = (): boolean => {
    return true;
  };

  const handleCreate = async (input: TriggerUpsertInput) => {
    if (validater()) {
      await createFn(input).then((result) => {
        if (result.data?.TriggerCreate.ok) {
          modalHook.closeModal();
        }
      });
    }
  };

  const handleUpdate = async (id: string, input: TriggerUpsertInput) => {
    if (validater()) {
      await updateFn(id, input).then((result) => {
        if (result.data?.TriggerUpdate.ok) {
          modalHook.closeModal();
        }
      });
    }
  };

  const handleDelete = () => {
    if (validater()) {
    }
  };


  return (
    <JDalign>
      {triggers.map((t) => (
        <JDcard mr="no" key={t._id}>
          <JDalign
            flex={{
              vCenter: true,
            }}
          >
            <JDtypho mb="normal" size="large" weight={600}>
              {autoSendCases.find((c) => c.value === t.event)?.label}
            </JDtypho>
            <div>
              {t.isEnabled ? (
                <JDbadge thema="positive">활성화</JDbadge>
              ) : (
                <JDbadge thema="grey2">비활성화</JDbadge>
              )}
            </div>
          </JDalign>
          <JDalign
            flex={{
              wrap: true,
              between: true,
              grow: true,
              vCenter: true,
            }}
          >
            <div>
              {<LabelValue label={LANG("template")} value={t.template.name} />}
            </div>
            <div>
              {
                <LabelValue
                  label={"태그"}
                  value={
                    t.tags
                      .map((tag) =>
                        tagsOp
                          ?.map(
                            (op) =>
                              op.ops.find((op) => op.value === tag.value)
                                ?.label || ""
                          )
                          .join("")
                      )
                      .join(", ") || "없음"
                  }
                />
              }
            </div>
            <JDbutton
              mr="no"
              mode="border"
              onClick={() => {
                modalHook.openModal({
                  mode: "update",
                  trigger: t,
                });
              }}
              label={LANG("modi")}
            />
          </JDalign>
        </JDcard>
      ))}
      <TriggerModal
        key={modalHook.info?.trigger?._id || ""}
        templatesOp={templatesOp}
        autoSendCases={autoSendCases}
        handleCreate={handleCreate}
        handleDelete={handleDelete}
        handleUpdate={handleUpdate}
        modalHook={modalHook}
        senders={senders}
        tagsOp={tagsOp}
      />
      <JDpreloader loading={totalLoading} floating />
    </JDalign>
  );
};

export default TriggerSetting;
