import type { Ref } from 'vue';

import type { ProductPickerItemDto } from '#/api/product';

import { message } from 'ant-design-vue';

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

interface CreatePickerActionsOptions {
  isPickerLoading: Ref<boolean>;
  isPickerOpen: Ref<boolean>;
  onPicked: (item: ProductPickerItemDto | undefined) => void;
  pickerKeyword: Ref<string>;
  pickerRows: Ref<ProductPickerItemDto[]>;
  pickerSelectedId: Ref<string>;
  selectedStoreId: Ref<string>;
}

export function createPickerActions(options: CreatePickerActionsOptions) {
  async function loadPickerProducts() {
    if (!options.selectedStoreId.value) {
      options.pickerRows.value = [];
      return;
    }

    options.isPickerLoading.value = true;
    try {
      options.pickerRows.value = await searchProductPickerApi({
        storeId: options.selectedStoreId.value,
        keyword: options.pickerKeyword.value.trim() || undefined,
        limit: 500,
      });
    } catch (error) {
      console.error(error);
      options.pickerRows.value = [];
      message.error('加载商品失败');
    } finally {
      options.isPickerLoading.value = false;
    }
  }

  async function openPicker(currentProductId?: string) {
    options.pickerKeyword.value = '';
    options.pickerSelectedId.value = currentProductId ?? '';
    options.pickerRows.value = [];
    options.isPickerOpen.value = true;
    await loadPickerProducts();
  }

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

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

  function setPickerSelectedId(value: string) {
    options.pickerSelectedId.value = value;
  }

  function submitPicker() {
    if (!options.pickerSelectedId.value) {
      message.warning('请选择商品');
      return;
    }

    const selected = options.pickerRows.value.find(
      (item) => item.id === options.pickerSelectedId.value,
    );
    options.onPicked(selected);
    options.isPickerOpen.value = false;
  }

  return {
    loadPickerProducts,
    openPicker,
    setPickerKeyword,
    setPickerOpen,
    setPickerSelectedId,
    submitPicker,
  };
}
