import type { Ref } from 'vue';

import type { CouponCardViewModel } from '#/views/marketing/coupon/types';

/**
 * 文件职责：优惠券卡片行操作。
 * 1. 封装启停与删除动作。
 * 2. 统一确认弹窗与成功提示。
 */
import { message, Modal } from 'ant-design-vue';

import {
  changeMarketingCouponStatusApi,
  deleteMarketingCouponApi,
} from '#/api/marketing';

interface CreateCardActionsOptions {
  loadCoupons: () => Promise<void>;
  selectedStoreId: Ref<string>;
}

export function createCardActions(options: CreateCardActionsOptions) {
  function enableCoupon(item: CouponCardViewModel) {
    openStatusConfirm(item, {
      actionText: '开放领取',
      confirmHint: '开放后，用户可按规则继续领取该优惠券。',
      status: 'enabled',
      successMessage: '优惠券已开放领取',
    });
  }

  function disableCoupon(item: CouponCardViewModel) {
    openStatusConfirm(item, {
      actionText: '暂停领取',
      confirmHint:
        '暂停后仅停止新用户领取，已领取优惠券仍可在有效期内继续使用。',
      status: 'disabled',
      successMessage: '优惠券已暂停领取',
    });
  }

  function openStatusConfirm(
    item: CouponCardViewModel,
    params: {
      actionText: '开放领取' | '暂停领取';
      confirmHint: string;
      status: 'disabled' | 'enabled';
      successMessage: string;
    },
  ) {
    if (!options.selectedStoreId.value) return;

    Modal.confirm({
      title: `确认${params.actionText}优惠券「${item.name}」吗？`,
      content: params.confirmHint,
      okText: `确认${params.actionText}`,
      cancelText: '取消',
      async onOk() {
        await updateStatus(
          item,
          params.status,
          params.actionText,
          params.successMessage,
        );
      },
    });
  }

  async function updateStatus(
    item: CouponCardViewModel,
    status: 'disabled' | 'enabled',
    actionText: '开放领取' | '暂停领取',
    successMessage: string,
  ) {
    if (!options.selectedStoreId.value) return;
    const feedbackKey = `coupon-status-${item.id}`;

    try {
      message.loading({
        content: `正在${actionText}优惠券...`,
        duration: 0,
        key: feedbackKey,
      });
      await changeMarketingCouponStatusApi({
        storeId: options.selectedStoreId.value,
        couponId: item.id,
        status,
      });
      message.success({ content: successMessage, key: feedbackKey });
      await options.loadCoupons();
    } catch (error) {
      console.error(error);
      message.error({
        content: `${actionText}失败，请稍后重试`,
        key: feedbackKey,
      });
    }
  }

  function removeCoupon(item: CouponCardViewModel) {
    if (!options.selectedStoreId.value) return;

    Modal.confirm({
      title: `确认删除优惠券「${item.name}」吗？`,
      okText: '确认删除',
      cancelText: '取消',
      async onOk() {
        await deleteMarketingCouponApi({
          storeId: options.selectedStoreId.value,
          couponId: item.id,
        });
        message.success('优惠券已删除');
        await options.loadCoupons();
      },
    });
  }

  return {
    disableCoupon,
    enableCoupon,
    removeCoupon,
  };
}
