import type { Ref } from 'vue';

import type { PointMallProductCardViewModel } from '#/views/member/points-mall/types';

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

import {
  changeMemberPointMallProductStatusApi,
  deleteMemberPointMallProductApi,
} from '#/api/member/points-mall';

interface CreateProductActionsOptions {
  canManage: Ref<boolean>;
  loadProductList: () => Promise<void>;
  selectedStoreId: Ref<string>;
}

export function createProductActions(options: CreateProductActionsOptions) {
  async function toggleStatus(item: PointMallProductCardViewModel) {
    if (!options.canManage.value) {
      return;
    }

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

    const targetStatus = item.status === 'enabled' ? 'disabled' : 'enabled';
    try {
      await changeMemberPointMallProductStatusApi({
        storeId: options.selectedStoreId.value,
        pointMallProductId: item.pointMallProductId,
        status: targetStatus,
      });
      message.success(targetStatus === 'enabled' ? '商品已上架' : '商品已下架');
      await options.loadProductList();
    } catch (error) {
      console.error(error);
      message.error('状态更新失败');
    }
  }

  function removeProduct(item: PointMallProductCardViewModel) {
    if (!options.canManage.value) {
      return;
    }

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

    Modal.confirm({
      title: '删除兑换商品',
      content: `确认删除「${item.name}」吗？删除后不可恢复。`,
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      async onOk() {
        try {
          await deleteMemberPointMallProductApi({
            storeId: options.selectedStoreId.value,
            pointMallProductId: item.pointMallProductId,
          });
          message.success('删除成功');
          await options.loadProductList();
        } catch (error) {
          console.error(error);
          message.error('删除失败');
        }
      },
    });
  }

  return {
    removeProduct,
    toggleStatus,
  };
}
