import type { Ref } from 'vue';

import type { ProductPickerItemDto } from '#/api/product';
import type { AddonGroupCardViewModel } from '#/views/product/addons/types';

/**
 * 文件职责：加料关联商品动作。
 * 1. 管理商品选择弹窗与检索状态。
 * 2. 提交加料组关联商品绑定。
 */
import { message } from 'ant-design-vue';

import {
  bindProductAddonGroupProductsApi,
  searchProductPickerApi,
} from '#/api/product';

interface CreatePickerActionsOptions {
  bindingGroupId: Ref<string>;
  isPickerLoading: Ref<boolean>;
  isPickerOpen: Ref<boolean>;
  isPickerSubmitting: Ref<boolean>;
  loadAddonGroups: () => Promise<void>;
  pickerKeyword: Ref<string>;
  pickerProducts: Ref<ProductPickerItemDto[]>;
  pickerSelectedIds: Ref<string[]>;
  pickerTitle: Ref<string>;
  selectedStoreId: Ref<string>;
}

export function createPickerActions(options: CreatePickerActionsOptions) {
  async function loadPickerProducts() {
    if (!options.selectedStoreId.value) {
      options.pickerProducts.value = [];
      return;
    }
    options.isPickerLoading.value = true;
    try {
      options.pickerProducts.value = await searchProductPickerApi({
        storeId: options.selectedStoreId.value,
        keyword: options.pickerKeyword.value.trim() || undefined,
        limit: 500,
      });
    } catch (error) {
      console.error(error);
      options.pickerProducts.value = [];
      message.error('加载商品失败');
    } finally {
      options.isPickerLoading.value = false;
    }
  }

  async function openBindProducts(item: AddonGroupCardViewModel) {
    options.bindingGroupId.value = item.id;
    options.pickerTitle.value = `关联商品 - ${item.name}`;
    options.pickerKeyword.value = '';
    options.pickerSelectedIds.value = [...item.productIds];
    options.pickerProducts.value = [];
    options.isPickerOpen.value = true;
    await loadPickerProducts();
  }

  function setPickerOpen(value: boolean) {
    options.isPickerOpen.value = value;
  }

  function setPickerKeyword(value: string) {
    options.pickerKeyword.value = value;
  }

  function togglePickerProduct(id: string) {
    if (options.pickerSelectedIds.value.includes(id)) {
      options.pickerSelectedIds.value = options.pickerSelectedIds.value.filter(
        (item) => item !== id,
      );
      return;
    }
    options.pickerSelectedIds.value = [...options.pickerSelectedIds.value, id];
  }

  async function submitPicker() {
    if (!options.selectedStoreId.value || !options.bindingGroupId.value) return;

    options.isPickerSubmitting.value = true;
    try {
      await bindProductAddonGroupProductsApi({
        storeId: options.selectedStoreId.value,
        groupId: options.bindingGroupId.value,
        productIds: [...options.pickerSelectedIds.value],
      });
      message.success('关联商品已更新');
      options.isPickerOpen.value = false;
      await options.loadAddonGroups();
    } catch (error) {
      console.error(error);
    } finally {
      options.isPickerSubmitting.value = false;
    }
  }

  return {
    loadPickerProducts,
    openBindProducts,
    setPickerKeyword,
    setPickerOpen,
    submitPicker,
    togglePickerProduct,
  };
}
