import React, { useState } from "react";
import {
  IUseModal,
  JDmodal,
  JDbutton,
  useSelect,
  JDselect,
  JDswitch,
  useSwitch,
} from "@janda-com/front";
import { lang as LANG } from "../../../lang/langFn";
import { ITrigger } from "../../../types/interface";
import { IselectedOption } from "@janda-com/front/build/types/interface";
import { TriggerUpsertInput, myManager_MyManager_data_senders } from "../../../types/api";
import { DEFAULT_TRIGGER } from "../../../types/defaults";

export type TUpdateFn = (id: string, input: TriggerUpsertInput) => void;

export type TCreateFn = (input: TriggerUpsertInput) => void;

export interface ITriggerModalInfo {
  trigger?: ITrigger;
  mode: "create" | "update";
}

export type TtagsOp = {
  key: string;
  ops: IselectedOption[];
}[];

export interface IChainProp {
  tagsOp?: TtagsOp;
  templatesOp: IselectedOption<string>[];
  autoSendCases: IselectedOption<string>[];
}

interface IProp extends IChainProp {
  senders: myManager_MyManager_data_senders[];
  modalHook: IUseModal<ITriggerModalInfo>;
  handleCreate: TCreateFn;
  handleDelete: () => void;
  handleUpdate: TUpdateFn;
}

export const TriggerModal: React.FC<IProp> = ({
  tagsOp: tagsOpProps,
  modalHook,
  autoSendCases,
  templatesOp,
  senders,
  handleCreate,
  handleDelete,
  handleUpdate,
}) => {
  const senederSelectOp = senders.map((s) => ({
    label: s.name,
    value: s._id
  }))
  let tagsOp: IselectedOption[] = [];
  tagsOpProps?.forEach((op) => {
    tagsOp = [...tagsOp, ...op.ops];
  });
  const { info, isOpen } = modalHook;
  if (!isOpen) return <div />;
  if (!info && isOpen) throw Error("must provide info");
  const { mode, trigger } = info!;

  const { event, template, tags, _id, isEnabled } = trigger || DEFAULT_TRIGGER;
  const targetEvent = autoSendCases.find((es) => es.value === event) || null;
  const targetSender = autoSendCases.find((es) => es.value === event) || null;
  const targetSenderOp = senederSelectOp.find(s => s.value === targetSender?.value) || senederSelectOp[0]; 
  const targetTemplate =
    templatesOp.find((t) => t.value === template._id) || null;

  const enableHook = useSwitch(isEnabled);
  const eventHook = useSelect(targetEvent, autoSendCases);
  const senderHook = useSelect(targetSenderOp, senederSelectOp);
  const templateHook = useSelect(targetTemplate, templatesOp);

  const [selectedOps, setSelectedOps] = useState<IselectedOption[]>(
    tags.map((t) => {
      return {
        label: tagsOp?.find((t) => t.value === t.value)?.label || "",
        value: t.value,
      };
    })
  );

  const isCreateMode = mode === "create";

  const sharedParam:TriggerUpsertInput = {
    tags:
      selectedOps?.map((op) => ({
        value: op.value,
        key:
          tagsOpProps?.find((ooo) => ooo.ops.find((o) => o.value === op.value))
            ?.key || "",
      })) || [],
    description: "",
    senderId: senderHook.selectedOption?.value,
    event: eventHook.selectedOption?.value,
    isEnabled: enableHook.checked,
    templateId: templateHook.selectedOption?.value,
  };

  useSelect;

  return (
    <JDmodal
      head={{
        element: (
          <div>
            <h6>{LANG("auto_trigger_mangae")}</h6>
            <JDswitch rtxt={LANG("is_auto_send_enable")} {...enableHook} />
          </div>
        ),
      }}
      foot={
        <div>
          {isCreateMode && (
            <JDbutton
              thema="primary"
              mode="flat"
              onClick={() => {
                handleCreate(sharedParam);
              }}
              label={LANG("do_create")}
            />
          )}
          {!isCreateMode && (
            <div>
              <JDbutton
                thema="primary"
                mode="flat"
                onClick={() => {
                  handleUpdate(_id, sharedParam);
                }}
                label={LANG("do_modify")}
              />
              <JDbutton
                thema="error"
                mode="flat"
                onClick={handleDelete}
                label={LANG("delete")}
              />
            </div>
          )}
        </div>
      }
      {...modalHook}
    >
      <div>
        <JDselect menuPlacement="top" label={LANG("sender")} {...eventHook} />
      </div>
      <div>
        <JDselect menuPlacement="top" label={LANG("event")} {...eventHook} />
      </div>
      <div>
        <JDselect
          menuPlacement="top"
          z={1}
          label={LANG("template")}
          {...templateHook}
        />
      </div>
      <div>
        <JDselect
          z={2}
          isMulti
          label={LANG("tags")}
          onChanges={(ops) => {
            setSelectedOps(ops);
          }}
          menuPlacement="top"
          selectedOptions={selectedOps}
          options={tagsOp}
        />
      </div>
    </JDmodal>
  );
};

export default TriggerModal;
