import type { Ref } from 'vue';

import type {
  PunchCardPickerCategoryItem,
  PunchCardPickerProductItem,
} from '#/views/marketing/punch-card/types';

/**
 * 文件职责：次卡二级商品选择抽屉动作。
 */
import { message } from 'ant-design-vue';

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

interface CreatePickerActionsOptions {
  isPickerLoading: Ref<boolean>;
  isPickerOpen: Ref<boolean>;
  pickerCategories: Ref<PunchCardPickerCategoryItem[]>;
  pickerCategoryFilterId: Ref<string>;
  pickerKeyword: Ref<string>;
  pickerProducts: Ref<PunchCardPickerProductItem[]>;
  pickerSelectedProductIds: Ref<string[]>;
  resolveStoreId: () => string;
}

export function createPickerActions(options: CreatePickerActionsOptions) {
  let onConfirm: ((productIds: string[]) => void) | null = null;

  function setPickerOpen(value: boolean) {
    options.isPickerOpen.value = value;
    if (!value) {
      onConfirm = null;
    }
  }

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

  function setPickerCategoryFilterId(value: string) {
    options.pickerCategoryFilterId.value = value;
  }

  function setPickerSelectedProductIds(value: string[]) {
    options.pickerSelectedProductIds.value = [...value];
  }

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

    options.pickerSelectedProductIds.value = [
      ...options.pickerSelectedProductIds.value,
      id,
    ];
  }

  async function loadPickerCategories() {
    const storeId = options.resolveStoreId();
    if (!storeId) {
      options.pickerCategories.value = [];
      return;
    }

    options.pickerCategories.value = await getProductCategoryListApi(storeId);
  }

  async function loadPickerProducts() {
    const storeId = options.resolveStoreId();
    if (!storeId) {
      options.pickerProducts.value = [];
      return;
    }

    options.pickerProducts.value = await searchProductPickerApi({
      storeId,
      keyword: options.pickerKeyword.value.trim() || undefined,
      categoryId: options.pickerCategoryFilterId.value || undefined,
      limit: 500,
    });
  }

  async function reloadPickerData() {
    if (!options.isPickerOpen.value) {
      return;
    }

    options.isPickerLoading.value = true;
    try {
      await Promise.all([loadPickerCategories(), loadPickerProducts()]);
    } catch (error) {
      console.error(error);
      options.pickerCategories.value = [];
      options.pickerProducts.value = [];
      message.error('加载商品失败');
    } finally {
      options.isPickerLoading.value = false;
    }
  }

  async function searchPickerProducts() {
    options.isPickerLoading.value = true;
    try {
      await loadPickerProducts();
    } catch (error) {
      console.error(error);
      options.pickerProducts.value = [];
      message.error('加载商品失败');
    } finally {
      options.isPickerLoading.value = false;
    }
  }

  async function openProductPicker(
    initialProductIds: string[],
    callback: (productIds: string[]) => void,
  ) {
    const storeId = options.resolveStoreId();
    if (!storeId) {
      message.warning('请先选择门店后再选择商品');
      return;
    }

    options.pickerSelectedProductIds.value = [...initialProductIds];
    options.pickerKeyword.value = '';
    options.pickerCategoryFilterId.value = '';
    onConfirm = callback;
    options.isPickerOpen.value = true;

    await reloadPickerData();
  }

  function submitPicker() {
    if (options.pickerSelectedProductIds.value.length === 0) {
      message.warning('请至少选择一个商品');
      return;
    }

    onConfirm?.([...options.pickerSelectedProductIds.value]);
    setPickerOpen(false);
  }

  return {
    openProductPicker,
    reloadPickerData,
    searchPickerProducts,
    setPickerCategoryFilterId,
    setPickerKeyword,
    setPickerOpen,
    setPickerSelectedProductIds,
    submitPicker,
    togglePickerProduct,
  };
}
