import type { Ref } from 'vue';

import type {
  FullReductionPickerCategoryItem,
  FullReductionPickerProductItem,
  FullReductionPickerTarget,
  FullReductionScopeForm,
} from '#/views/marketing/full-reduction/types';

/**
 * 文件职责：满减活动二级抽屉（商品范围选择）动作。
 * 1. 管理范围选择抽屉开关、检索和列表加载。
 * 2. 统一分类/商品选择结果回填。
 */
import { message } from 'ant-design-vue';

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

import { cloneScopeForm } from './helpers';

interface OpenPickerOptions {
  allowAll: boolean;
  initialScope: FullReductionScopeForm;
  scopeStoreId: string;
  target: FullReductionPickerTarget;
  title: string;
}

interface CreatePickerActionsOptions {
  isPickerLoading: Ref<boolean>;
  isPickerOpen: Ref<boolean>;
  pickerAllowAll: Ref<boolean>;
  pickerCategories: Ref<FullReductionPickerCategoryItem[]>;
  pickerCategoryFilterId: Ref<string>;
  pickerKeyword: Ref<string>;
  pickerProducts: Ref<FullReductionPickerProductItem[]>;
  pickerScope: Ref<FullReductionScopeForm>;
  pickerTarget: Ref<FullReductionPickerTarget>;
  pickerTitle: Ref<string>;
  resolveOperationStoreId: () => string;
}

export function createPickerActions(options: CreatePickerActionsOptions) {
  let activeScopeStoreId = '';
  let onConfirmScope: ((scope: FullReductionScopeForm) => void) | null = null;

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

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

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

  function setPickerScopeType(value: FullReductionScopeForm['scopeType']) {
    if (!options.pickerAllowAll.value && value === 'all') {
      return;
    }

    options.pickerScope.value = {
      scopeType: value,
      categoryIds:
        value === 'category' ? options.pickerScope.value.categoryIds : [],
      productIds:
        value === 'product' ? options.pickerScope.value.productIds : [],
    };
  }

  function setPickerCategoryIds(ids: string[]) {
    options.pickerScope.value = {
      ...options.pickerScope.value,
      categoryIds: [...ids],
    };
  }

  function setPickerProductIds(ids: string[]) {
    options.pickerScope.value = {
      ...options.pickerScope.value,
      productIds: [...ids],
    };
  }

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

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

  async function loadPickerProducts() {
    const storeId = activeScopeStoreId || options.resolveOperationStoreId();
    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 reloadPickerList() {
    if (!options.isPickerOpen.value) {
      return;
    }

    options.isPickerLoading.value = true;
    try {
      await loadPickerCategories();
      if (options.pickerScope.value.scopeType === 'product') {
        await loadPickerProducts();
      } else {
        options.pickerProducts.value = [];
      }
    } catch (error) {
      console.error(error);
      options.pickerCategories.value = [];
      options.pickerProducts.value = [];
      message.error('加载可选范围失败');
    } finally {
      options.isPickerLoading.value = false;
    }
  }

  async function searchPickerProducts() {
    if (options.pickerScope.value.scopeType !== 'product') {
      return;
    }

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

  async function openPicker(
    params: OpenPickerOptions,
    onConfirm: (scope: FullReductionScopeForm) => void,
  ) {
    const resolvedStoreId =
      params.scopeStoreId || options.resolveOperationStoreId();
    if (!resolvedStoreId) {
      message.warning('请先选择门店后再配置商品范围');
      return;
    }

    activeScopeStoreId = resolvedStoreId;
    onConfirmScope = onConfirm;
    options.pickerTitle.value = params.title;
    options.pickerTarget.value = params.target;
    options.pickerAllowAll.value = params.allowAll;
    options.pickerKeyword.value = '';
    options.pickerCategoryFilterId.value = '';

    const scope = cloneScopeForm(params.initialScope);
    if (!params.allowAll && scope.scopeType === 'all') {
      scope.scopeType = 'category';
    }
    options.pickerScope.value = scope;
    options.isPickerOpen.value = true;

    await reloadPickerList();
  }

  function submitPicker() {
    const scope = options.pickerScope.value;
    if (!options.pickerAllowAll.value && scope.scopeType === 'all') {
      message.warning('当前范围不支持全部商品，请选择分类或商品');
      return;
    }

    if (scope.scopeType === 'category' && scope.categoryIds.length === 0) {
      message.warning('请至少选择一个分类');
      return;
    }

    if (scope.scopeType === 'product' && scope.productIds.length === 0) {
      message.warning('请至少选择一个商品');
      return;
    }

    onConfirmScope?.(cloneScopeForm(scope));
    setPickerOpen(false);
  }

  return {
    openPicker,
    reloadPickerList,
    searchPickerProducts,
    setPickerCategoryFilterId,
    setPickerCategoryIds,
    setPickerKeyword,
    setPickerOpen,
    setPickerProductIds,
    setPickerScopeType,
    submitPicker,
  };
}
