import React, { Fragment, useState } from "react";
import { ITemplate, IselectedOption } from "../../../types/interface";
import {
  InputText,
  useInput,
  IUseModal,
  JDlabel,
  JDmodal,
  JDbutton,
  JDselect,
} from "@janda-com/front";
import { DEFAULT_TEMPLATE } from "../../../types/const";
import { lang as LANG } from "../../../lang/langFn";
import { ISmsConfig } from "../../../app";
import { TController } from "../SmsTemplateSettingWrap";
import MsgTypeViewer from "../../../atom/MsgTypeViewer";
import { JDmodalConfigProps } from "@janda-com/front/build/components/modal/Modal";

export interface IChainProp {}

export interface ISmsTemplateModalInfo {
  template?: ITemplate;
  isAdd: boolean;
}

interface Iprops extends JDmodalConfigProps, IChainProp {
  config: ISmsConfig;
  modalHook: IUseModal<ISmsTemplateModalInfo>;
  controller: TController;
  totalLoading: boolean;
}

type TtriggerList = {
  label: string;
  value: string;
  id?: any;
}[];

const defualtInfo = {
  isAdd: false,
  template: undefined,
};

const SmsTemplateModal: React.FC<Iprops> = ({
  modalHook,
  controller,
  config,
  totalLoading,
  ...props
}) => {
  const { createFn, deleteFn, updateFn } = controller;
  const { smsReplaceKeys, autoSendCases, msgToTemplate } = config;
  const { template, isAdd } = modalHook.info || defualtInfo;
  const { _id: templateId, content, name, triggers } =
    template || DEFAULT_TEMPLATE;
  const triggerList: TtriggerList = triggers.map((t) => ({
    label: autoSendCases.find((as) => as.value === t.event)?.label || "",
    value: t.event,
    id: t._id,
  }));

  const [events, setEvents] = useState(triggerList);

  const [messageValue, setMessage] = useState(content);
  const templateTitleHook = useInput(name);

  const hanldeTemplateBtnClick = (label: string) => {
    setMessage(`${messageValue} [${label}]`);
  };

  const eventMap = (events: TtriggerList) => {
    return events.map((ev) => ({
      params: {
        event: ev.value,
        tags: [],
      },
      triggerId: ev.id,
    }));
  };
  const sharedVaraible = {
    content: msgToTemplate(messageValue),
    description: "",
    name: templateTitleHook.value,
  };

  const handleCreateBtnClick = async () => {
    const result = await createFn(sharedVaraible, {
      triggerUpsertInputs: eventMap(events),
    });
    if (result) modalHook.closeModal();
  };

  const handleDeleteBtnClick = async () => {
    const result = deleteFn({
      templateId,
    });
    if (result) modalHook.closeModal();
  };
  const handleUpdateBtnClick = async () => {
    const result = await updateFn(
      {
        params: sharedVaraible,
        templateId,
      },
      {
        triggerUpsertInputs: eventMap(events),
      }
    );
    if (result) modalHook.closeModal();
  };

  return (
    <JDmodal
      {...props}
      loading={totalLoading}
      foot={
        <div>
          <JDbutton
            hide={!isAdd}
            id="CreateTemplateBtn"
            mode="flat"
            size="small"
            label={LANG("do_create")}
            thema="primary"
            onClick={handleCreateBtnClick}
          />
          <JDbutton
            id="UpdateTemplateBtn"
            mode="flat"
            size="small"
            label={LANG("do_modify")}
            thema="primary"
            disabled={isAdd}
            onClick={handleUpdateBtnClick}
          />
          <JDbutton
            id="DeleteTemplateBtn"
            mode="flat"
            size="small"
            label={LANG("delete")}
            thema="error"
            disabled={isAdd}
            onClick={handleDeleteBtnClick}
          />
        </div>
      }
      head={{
        title: LANG("templateCreateHeader"),
      }}
      className="smsTemplateModal"
      {...modalHook}
    >
      <Fragment>
        <div className="smsTemplateModal__contentWrap">
          <div>
            <InputText
              require
              id="TemplateTitleInput"
              {...templateTitleHook}
              label={LANG("template_title")}
            />
          </div>
          <div className="smsTemplateModal__msgWrap">
            <InputText
              mr="no"
              id="MessageInput"
              value={messageValue}
              // @ts-ignore
              onChange={(v: any) => {
                setMessage(v);
              }}
              mb="huge"
              label={LANG("msg")}
              textarea
              doubleHeight
            />
            <MsgTypeViewer
              msg={messageValue}
              className="smsTemplateModal__typeViewer"
            />
          </div>
          <div>
            <JDselect
              onChanges={(ops) => {
                setEvents(ops);
              }}
              options={autoSendCases}
              selectedOptions={events}
              id="AutoSendSelect"
              autoSize
              isMulti
              menuPlacement="top"
              label={LANG("auto_send_case")}
            />
          </div>
          <div>
            <div>
              <JDlabel txt={LANG("template_msg")} />
            </div>
            {/* TODO 이건 상품으로부터 전해와야함 */}
            {smsReplaceKeys?.map((op: IselectedOption) => {
              const { label, value } = op;
              return (
                <JDbutton
                  onClick={() => {
                    hanldeTemplateBtnClick(label);
                  }}
                  size="small"
                  mode="border"
                  key={`templateBtn${templateId}${value}`}
                  label={label}
                />
              );
            })}
          </div>
        </div>
      </Fragment>
    </JDmodal>
  );
};

export default SmsTemplateModal;
