import type { ComputedRef, Ref } from 'vue';

import type {
  ProductCategoryManageDto,
  ProductPickerItemDto,
} from '#/api/product';
import type { ProductPreviewItem } from '#/views/product/category/types';

/**
 * 文件职责：分类商品绑定动作。
 * 1. 管理商品选择弹窗与关键字检索。
 * 2. 执行商品绑定与解绑操作。
 */
import { message, Modal } from 'ant-design-vue';

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

interface CreatePickerActionsOptions {
  categoryProducts: Ref<ProductPreviewItem[]>;
  isPickerLoading: Ref<boolean>;
  isPickerOpen: Ref<boolean>;
  isPickerSubmitting: Ref<boolean>;
  loadCategories: (preferredCategoryId?: string) => Promise<void>;
  pickerKeyword: Ref<string>;
  pickerProducts: Ref<ProductPickerItemDto[]>;
  pickerSelectedIds: Ref<string[]>;
  selectedCategory: ComputedRef<ProductCategoryManageDto | undefined>;
  selectedStoreId: Ref<string>;
}

export function createPickerActions(options: CreatePickerActionsOptions) {
  async function openProductPicker() {
    if (!options.selectedStoreId.value || !options.selectedCategory.value) {
      return;
    }
    options.pickerKeyword.value = '';
    options.pickerProducts.value = [];
    options.pickerSelectedIds.value = [];
    options.isPickerOpen.value = true;
    await loadPickerProducts();
  }

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

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

  async function loadPickerProducts() {
    if (!options.selectedStoreId.value || !options.selectedCategory.value) {
      options.pickerProducts.value = [];
      return;
    }

    options.isPickerLoading.value = true;
    try {
      const list = await searchProductPickerApi({
        storeId: options.selectedStoreId.value,
        keyword: options.pickerKeyword.value.trim() || undefined,
        limit: 500,
      });
      const currentIds = new Set(
        options.categoryProducts.value.map((item) => item.id),
      );
      options.pickerProducts.value = list.filter(
        (item) => !currentIds.has(item.id),
      );
    } catch (error) {
      console.error(error);
      options.pickerProducts.value = [];
      message.error('加载可选商品失败');
    } finally {
      options.isPickerLoading.value = false;
    }
  }

  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 submitProductPicker() {
    const current = options.selectedCategory.value;
    if (!options.selectedStoreId.value || !current) return;
    if (options.pickerSelectedIds.value.length === 0) {
      message.warning('请至少选择一个商品');
      return;
    }

    options.isPickerSubmitting.value = true;
    try {
      await bindCategoryProductsApi({
        storeId: options.selectedStoreId.value,
        categoryId: current.id,
        productIds: [...options.pickerSelectedIds.value],
      });
      message.success('商品已添加到分类');
      options.isPickerOpen.value = false;
      await options.loadCategories(current.id);
    } catch (error) {
      console.error(error);
    } finally {
      options.isPickerSubmitting.value = false;
    }
  }

  function unbindProduct(item: ProductPreviewItem) {
    const current = options.selectedCategory.value;
    if (!options.selectedStoreId.value || !current) return;

    Modal.confirm({
      title: `确认将「${item.name}」移出当前分类吗？`,
      content: '移出后商品会自动归入其他分类。',
      okText: '确认移出',
      cancelText: '取消',
      async onOk() {
        await unbindCategoryProductApi({
          storeId: options.selectedStoreId.value,
          categoryId: current.id,
          productId: item.id,
        });
        message.success('商品已移出');
        await options.loadCategories(current.id);
      },
    });
  }

  return {
    loadPickerProducts,
    openProductPicker,
    setPickerKeyword,
    setPickerOpen,
    submitProductPicker,
    togglePickerProduct,
    unbindProduct,
  };
}
