import type { Ref } from 'vue';

import type { MessageTemplateEditorForm } from '#/views/member/message-reach/types';

import { message, Modal } from 'ant-design-vue';

import {
  deleteMemberMessageTemplateApi,
  getMemberMessageTemplateDetailApi,
  saveMemberMessageTemplateApi,
} from '#/api/member/message-reach';

import {
  mapTemplateEditorFormToSavePayload,
  resetTemplateEditorForm,
} from './helpers';

interface CreateTemplateActionsOptions {
  canManage: Ref<boolean>;
  form: MessageTemplateEditorForm;
  isTemplateEditorLoading: Ref<boolean>;
  isTemplateEditorOpen: Ref<boolean>;
  isTemplateSubmitting: Ref<boolean>;
  loadTemplateList: () => Promise<void>;
  mode: Ref<'create' | 'edit'>;
}

export function createTemplateActions(options: CreateTemplateActionsOptions) {
  function setTemplateEditorOpen(value: boolean) {
    options.isTemplateEditorOpen.value = value;
  }

  function setTemplateName(value: string) {
    options.form.name = value;
  }

  function setTemplateCategory(value: 'marketing' | 'notice' | 'recall') {
    options.form.category = value;
  }

  function setTemplateContent(value: string) {
    options.form.content = value;
  }

  function openCreateTemplateModal() {
    if (!options.canManage.value) {
      return;
    }

    options.mode.value = 'create';
    resetTemplateEditorForm(options.form);
    options.isTemplateEditorOpen.value = true;
  }

  async function openEditTemplateModal(templateId: string) {
    if (!options.canManage.value) {
      return;
    }

    options.isTemplateEditorLoading.value = true;
    try {
      const detail = await getMemberMessageTemplateDetailApi({ templateId });
      options.mode.value = 'edit';
      options.form.templateId = detail.templateId;
      options.form.name = detail.name;
      options.form.category = detail.category;
      options.form.content = detail.content;
      options.isTemplateEditorOpen.value = true;
    } catch (error) {
      console.error(error);
      message.error('加载模板详情失败');
    } finally {
      options.isTemplateEditorLoading.value = false;
    }
  }

  async function submitTemplate() {
    if (!options.canManage.value) {
      return;
    }

    const payload = mapTemplateEditorFormToSavePayload(options.form);
    if (!payload.name) {
      message.warning('请输入模板名称');
      return;
    }
    if (!payload.content) {
      message.warning('请输入模板内容');
      return;
    }

    options.isTemplateSubmitting.value = true;
    try {
      await saveMemberMessageTemplateApi(payload);
      message.success(
        options.mode.value === 'create' ? '模板创建成功' : '模板保存成功',
      );
      options.isTemplateEditorOpen.value = false;
      await options.loadTemplateList();
    } catch (error) {
      console.error(error);
      message.error(
        options.mode.value === 'create' ? '模板创建失败' : '模板保存失败',
      );
    } finally {
      options.isTemplateSubmitting.value = false;
    }
  }

  function removeTemplate(templateId: string) {
    if (!options.canManage.value) {
      return;
    }

    Modal.confirm({
      title: '确认删除模板？',
      content: '删除后不可恢复，且不影响已发送消息。',
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      async onOk() {
        try {
          await deleteMemberMessageTemplateApi({ templateId });
          message.success('删除成功');
          await options.loadTemplateList();
        } catch (error) {
          console.error(error);
          message.error('删除失败');
        }
      },
    });
  }

  return {
    openCreateTemplateModal,
    openEditTemplateModal,
    removeTemplate,
    setTemplateCategory,
    setTemplateContent,
    setTemplateEditorOpen,
    setTemplateName,
    submitTemplate,
  };
}
