import type { Ref } from 'vue';

import type { PunchCardTemplateCardViewModel } from '#/views/marketing/punch-card/types';

/**
 * 文件职责：次卡卡片动作（上下架/删除）。
 */
import { message, Modal } from 'ant-design-vue';

import {
  changeMarketingPunchCardStatusApi,
  deleteMarketingPunchCardApi,
} from '#/api/marketing';

interface CreateCardActionsOptions {
  canManage: Ref<boolean>;
  loadPunchCardList: () => Promise<void>;
  loadUsageRecords: () => Promise<void>;
  selectedStoreId: Ref<string>;
}

export function createCardActions(options: CreateCardActionsOptions) {
  async function toggleStatus(item: PunchCardTemplateCardViewModel) {
    if (!options.canManage.value) {
      return;
    }

    if (!options.selectedStoreId.value) {
      message.warning('请先选择门店');
      return;
    }

    const nextStatus = item.status === 'enabled' ? 'disabled' : 'enabled';
    const confirmText = nextStatus === 'enabled' ? '上架' : '下架';

    Modal.confirm({
      title: `${confirmText}次卡`,
      content: `确认${confirmText}「${item.name}」吗？`,
      onOk: async () => {
        try {
          await changeMarketingPunchCardStatusApi({
            storeId: options.selectedStoreId.value,
            punchCardId: item.id,
            status: nextStatus,
          });
          message.success(`${confirmText}成功`);
          await Promise.all([
            options.loadPunchCardList(),
            options.loadUsageRecords(),
          ]);
        } catch (error) {
          console.error(error);
          message.error(`${confirmText}失败`);
        }
      },
    });
  }

  async function removeCard(item: PunchCardTemplateCardViewModel) {
    if (!options.canManage.value) {
      return;
    }

    if (!options.selectedStoreId.value) {
      message.warning('请先选择门店');
      return;
    }

    Modal.confirm({
      title: '删除次卡',
      content: `确认删除「${item.name}」吗？删除后不可恢复。`,
      okButtonProps: { danger: true },
      onOk: async () => {
        try {
          await deleteMarketingPunchCardApi({
            storeId: options.selectedStoreId.value,
            punchCardId: item.id,
          });
          message.success('删除成功');
          await Promise.all([
            options.loadPunchCardList(),
            options.loadUsageRecords(),
          ]);
        } catch (error) {
          console.error(error);
          message.error('删除失败');
        }
      },
    });
  }

  return {
    removeCard,
    toggleStatus,
  };
}
