import type { Ref } from 'vue';

import type {
  ProductAddonGroupDto,
  SaveProductAddonGroupDto,
} from '#/api/product';
import type { AddonGroupCardViewModel } from '#/views/product/addons/types';

/**
 * 文件职责：加料组卡片动作。
 * 1. 处理卡片级启用/删除操作。
 * 2. 处理加料项改名与移除。
 */
import { h } from 'vue';

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

import {
  changeProductAddonGroupStatusApi,
  deleteProductAddonGroupApi,
  saveProductAddonGroupApi,
} from '#/api/product';

interface CreateGroupActionsOptions {
  loadAddonGroups: () => Promise<void>;
  selectedStoreId: Ref<string>;
}

export function createGroupActions(options: CreateGroupActionsOptions) {
  async function changeGroupStatus(
    item: AddonGroupCardViewModel,
    status: 'disabled' | 'enabled',
    successMessage: string,
  ) {
    if (!options.selectedStoreId.value) return;
    try {
      await changeProductAddonGroupStatusApi({
        storeId: options.selectedStoreId.value,
        groupId: item.id,
        status,
      });
      message.success(successMessage);
      await options.loadAddonGroups();
    } catch (error) {
      console.error(error);
      message.error('加料组状态更新失败');
    }
  }

  function removeGroup(item: AddonGroupCardViewModel) {
    if (!options.selectedStoreId.value) return;
    Modal.confirm({
      title: `确认删除加料组「${item.name}」吗？`,
      okText: '确认删除',
      cancelText: '取消',
      async onOk() {
        await deleteProductAddonGroupApi({
          storeId: options.selectedStoreId.value,
          groupId: item.id,
        });
        message.success('加料组已删除');
        await options.loadAddonGroups();
      },
    });
  }

  async function enableGroup(item: AddonGroupCardViewModel) {
    await changeGroupStatus(item, 'enabled', '加料组已启用');
  }

  function disableGroup(item: AddonGroupCardViewModel) {
    if (!options.selectedStoreId.value) return;
    Modal.confirm({
      title: `确认停用加料组「${item.name}」吗？`,
      okText: '确认停用',
      cancelText: '取消',
      async onOk() {
        await changeGroupStatus(item, 'disabled', '加料组已停用');
      },
    });
  }

  async function saveGroupInline(
    group: AddonGroupCardViewModel,
    items: ProductAddonGroupDto['items'],
  ) {
    if (!options.selectedStoreId.value) return;

    const payload: SaveProductAddonGroupDto = {
      storeId: options.selectedStoreId.value,
      id: group.id,
      name: group.name,
      description: group.description,
      required: group.required,
      minSelect: group.minSelect,
      maxSelect: group.maxSelect,
      sort: group.sort,
      status: group.status,
      productIds: [...group.productIds],
      items: items.map((item, index) => ({
        id: item.id || undefined,
        name: item.name.trim(),
        price: Number(item.price.toFixed(2)),
        stock: item.stock,
        sort: index + 1,
        status: item.status,
      })),
    };

    await saveProductAddonGroupApi(payload);
  }

  function renameItem(payload: {
    group: AddonGroupCardViewModel;
    itemId: string;
  }) {
    const currentItem = payload.group.items.find(
      (item) => item.id === payload.itemId,
    );
    if (!currentItem) return;

    let draftName = currentItem.name;
    Modal.confirm({
      title: `改名 - ${currentItem.name}`,
      okText: '确认',
      cancelText: '取消',
      content: () =>
        h(Input, {
          value: draftName,
          maxlength: 30,
          placeholder: '请输入新名称',
          'onUpdate:value': (value: string) => {
            draftName = value;
          },
        }),
      async onOk() {
        const nextName = draftName.trim();
        if (!nextName) {
          message.warning('加料项名称不能为空');
          throw new Error('invalid-name');
        }

        const nextItems = payload.group.items.map((item) =>
          item.id === payload.itemId ? { ...item, name: nextName } : item,
        );
        const uniqueNames = new Set(
          nextItems.map((item) => item.name.toLowerCase()),
        );
        if (uniqueNames.size !== nextItems.length) {
          message.warning('加料项名称不能重复');
          throw new Error('duplicate-name');
        }

        await saveGroupInline(payload.group, nextItems);
        message.success('加料项名称已更新');
        await options.loadAddonGroups();
      },
    });
  }

  function removeCardItem(payload: {
    group: AddonGroupCardViewModel;
    itemId: string;
  }) {
    if (payload.group.items.length <= 1) {
      message.warning('至少保留一个加料项');
      return;
    }

    const currentItem = payload.group.items.find(
      (item) => item.id === payload.itemId,
    );
    if (!currentItem) return;

    Modal.confirm({
      title: `确认移除选项「${currentItem.name}」吗？`,
      okText: '确认移除',
      cancelText: '取消',
      async onOk() {
        const nextItems = payload.group.items.filter(
          (item) => item.id !== payload.itemId,
        );
        await saveGroupInline(payload.group, nextItems);
        message.success('加料项已移除');
        await options.loadAddonGroups();
      },
    });
  }

  return {
    disableGroup,
    enableGroup,
    removeCardItem,
    removeGroup,
    renameItem,
  };
}
