import type { Ref } from 'vue';

import type {
  FlashSaleEditorProductForm,
  FlashSalePickerCategoryItem,
  FlashSalePickerProductItem,
} from '#/views/marketing/flash-sale/types';

/**
 * 文件职责：限时折扣商品选择弹窗动作。
 */
import { message } from 'ant-design-vue';

import {
  getMarketingFlashSalePickerCategoriesApi,
  getMarketingFlashSalePickerProductsApi,
} from '#/api/marketing';

import { createDefaultFlashSaleProductForm } from './constants';

interface OpenPickerOptions {
  selectedProducts: FlashSaleEditorProductForm[];
  selectedProductIds: string[];
  storeId: string;
}

interface CreatePickerActionsOptions {
  isPickerLoading: Ref<boolean>;
  isPickerOpen: Ref<boolean>;
  pickerCategories: Ref<FlashSalePickerCategoryItem[]>;
  pickerCategoryFilterId: Ref<string>;
  pickerKeyword: Ref<string>;
  pickerProducts: Ref<FlashSalePickerProductItem[]>;
  pickerSelectedProductIds: Ref<string[]>;
}

export function createPickerActions(options: CreatePickerActionsOptions) {
  let activeStoreId = '';
  let selectedProductSnapshot = new Map<string, FlashSaleEditorProductForm>();
  let onConfirmProducts:
    | ((products: FlashSaleEditorProductForm[]) => void)
    | null = null;

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

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

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

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

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

  function toggleAllProducts(checked: boolean) {
    if (!checked) {
      const visibleIds = new Set(
        options.pickerProducts.value.map((item) => item.id),
      );
      options.pickerSelectedProductIds.value =
        options.pickerSelectedProductIds.value.filter(
          (item) => !visibleIds.has(item),
        );
      return;
    }

    const merged = new Set(options.pickerSelectedProductIds.value);
    for (const item of options.pickerProducts.value) {
      merged.add(item.id);
    }
    options.pickerSelectedProductIds.value = [...merged];
  }

  async function loadPickerCategories() {
    if (!activeStoreId) {
      options.pickerCategories.value = [];
      return;
    }
    options.pickerCategories.value =
      await getMarketingFlashSalePickerCategoriesApi({
        storeId: activeStoreId,
      });
  }

  async function loadPickerProducts() {
    if (!activeStoreId) {
      options.pickerProducts.value = [];
      return;
    }
    options.pickerProducts.value = await getMarketingFlashSalePickerProductsApi(
      {
        storeId: activeStoreId,
        categoryId: options.pickerCategoryFilterId.value || undefined,
        keyword: options.pickerKeyword.value.trim() || undefined,
        limit: 500,
      },
    );
  }

  async function reloadPickerList() {
    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 openPicker(
    pickerOptions: OpenPickerOptions,
    onConfirm: (products: FlashSaleEditorProductForm[]) => void,
  ) {
    if (!pickerOptions.storeId) {
      message.warning('请先选择具体门店后再添加商品');
      return;
    }

    activeStoreId = pickerOptions.storeId;
    onConfirmProducts = onConfirm;
    selectedProductSnapshot = new Map(
      pickerOptions.selectedProducts.map((item) => [
        item.productId,
        createDefaultFlashSaleProductForm(item),
      ]),
    );
    options.pickerKeyword.value = '';
    options.pickerCategoryFilterId.value = '';
    options.pickerSelectedProductIds.value = [
      ...pickerOptions.selectedProductIds,
    ];
    options.isPickerOpen.value = true;

    await reloadPickerList();
  }

  function submitPicker() {
    const selectedIds = new Set(options.pickerSelectedProductIds.value);
    const currentProductMap = new Map(
      options.pickerProducts.value.map((item) => [
        item.id,
        createDefaultFlashSaleProductForm({
          productId: item.id,
          categoryId: item.categoryId,
          categoryName: item.categoryName,
          name: item.name,
          spuCode: item.spuCode,
          status: item.status,
          originalPrice: item.price,
          discountPrice: item.price,
          perUserLimit: null,
          soldCount: 0,
        }),
      ]),
    );

    const selectedProducts = [...selectedIds]
      .map(
        (productId) =>
          currentProductMap.get(productId) ??
          selectedProductSnapshot.get(productId),
      )
      .filter(Boolean) as FlashSaleEditorProductForm[];

    if (selectedProducts.length === 0) {
      message.warning('请至少选择一个商品');
      return;
    }

    onConfirmProducts?.(selectedProducts);
    setPickerOpen(false);
  }

  return {
    openPicker,
    reloadPickerList,
    setPickerCategoryFilterId,
    setPickerKeyword,
    setPickerOpen,
    setPickerSelectedProductIds,
    submitPicker,
    toggleAllProducts,
    togglePickerProduct,
  };
}
