import type { AddonEditorForm, AddonGroupCardViewModel } from '../types';

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

/**
 * 文件职责：加料管理页面状态与行为编排。
 * 1. 管理门店、加料组卡片、统计与筛选状态。
 * 2. 封装加料组新增编辑、选项改名移除、关联商品流程。
 */
import { computed, onMounted, reactive, ref, watch } from 'vue';

import { createDefaultAddonItem } from './addons-page/constants';
import { createDataActions } from './addons-page/data-actions';
import { createDrawerActions } from './addons-page/drawer-actions';
import { createGroupActions } from './addons-page/group-actions';
import { createPickerActions } from './addons-page/picker-actions';

export function useProductAddonsPage() {
  const stores = ref<StoreListItemDto[]>([]);
  const selectedStoreId = ref('');
  const isStoreLoading = ref(false);

  const rows = ref<AddonGroupCardViewModel[]>([]);
  const isLoading = ref(false);
  const keyword = ref('');

  const isDrawerOpen = ref(false);
  const isDrawerSubmitting = ref(false);
  const drawerMode = ref<'create' | 'edit'>('create');
  const editingGroupId = ref('');
  const editingGroupName = ref('');
  const editingProductIds = ref<string[]>([]);

  const form = reactive<AddonEditorForm>({
    name: '',
    description: '',
    required: false,
    minSelect: 0,
    maxSelect: 1,
    sort: 1,
    status: 'enabled',
    items: [createDefaultAddonItem()],
  });

  const isPickerOpen = ref(false);
  const isPickerLoading = ref(false);
  const isPickerSubmitting = ref(false);
  const pickerTitle = ref('关联商品');
  const pickerKeyword = ref('');
  const pickerProducts = ref<ProductPickerItemDto[]>([]);
  const pickerSelectedIds = ref<string[]>([]);
  const bindingGroupId = ref('');

  const storeOptions = computed(() =>
    stores.value.map((item) => ({
      label: item.name,
      value: item.id,
    })),
  );

  const filteredRows = computed(() => {
    const normalized = keyword.value.trim().toLowerCase();
    if (!normalized) return rows.value;
    return rows.value.filter((item) =>
      item.name.toLowerCase().includes(normalized),
    );
  });

  const groupCount = computed(() => rows.value.length);

  const optionCount = computed(() =>
    rows.value.reduce((sum, item) => sum + item.items.length, 0),
  );

  const relatedProductCount = computed(() =>
    rows.value.reduce((sum, item) => sum + item.productCount, 0),
  );

  const drawerTitle = computed(() =>
    drawerMode.value === 'create'
      ? '添加加料组'
      : `编辑加料组 - ${editingGroupName.value}`,
  );

  const drawerSubmitText = computed(() =>
    drawerMode.value === 'create' ? '确认保存' : '保存修改',
  );

  const { loadAddonGroups, loadStores } = createDataActions({
    stores,
    selectedStoreId,
    isStoreLoading,
    rows,
    isLoading,
  });

  function setSelectedStoreId(value: string) {
    selectedStoreId.value = value;
  }

  function setKeyword(value: string) {
    keyword.value = value;
  }

  const {
    addItem,
    openCreateDrawer,
    openEditDrawer,
    removeItem,
    setDrawerOpen,
    setFormDescription,
    setFormMaxSelect,
    setFormMinSelect,
    setFormName,
    setFormRequired,
    setItemName,
    setItemPrice,
    setItemStock,
    submitDrawer,
  } = createDrawerActions({
    drawerMode,
    editingGroupId,
    editingGroupName,
    editingProductIds,
    form,
    isDrawerOpen,
    isDrawerSubmitting,
    loadAddonGroups,
    rows,
    selectedStoreId,
  });

  const { disableGroup, enableGroup, removeCardItem, removeGroup, renameItem } =
    createGroupActions({
      selectedStoreId,
      loadAddonGroups,
    });

  const {
    loadPickerProducts,
    openBindProducts,
    setPickerKeyword,
    setPickerOpen,
    submitPicker,
    togglePickerProduct,
  } = createPickerActions({
    selectedStoreId,
    bindingGroupId,
    isPickerOpen,
    isPickerLoading,
    isPickerSubmitting,
    pickerKeyword,
    pickerProducts,
    pickerSelectedIds,
    pickerTitle,
    loadAddonGroups,
  });

  watch(selectedStoreId, () => {
    keyword.value = '';
    void loadAddonGroups();
  });

  onMounted(loadStores);

  return {
    addItem,
    disableGroup,
    drawerSubmitText,
    drawerTitle,
    enableGroup,
    filteredRows,
    form,
    groupCount,
    isDrawerOpen,
    isDrawerSubmitting,
    isLoading,
    isPickerLoading,
    isPickerOpen,
    isPickerSubmitting,
    isStoreLoading,
    keyword,
    loadPickerProducts,
    openBindProducts,
    openCreateDrawer,
    openEditDrawer,
    optionCount,
    pickerKeyword,
    pickerProducts,
    pickerSelectedIds,
    pickerTitle,
    relatedProductCount,
    removeCardItem,
    removeGroup,
    removeItem,
    renameItem,
    selectedStoreId,
    setDrawerOpen,
    setFormDescription,
    setFormMaxSelect,
    setFormMinSelect,
    setFormName,
    setFormRequired,
    setItemName,
    setItemPrice,
    setItemStock,
    setKeyword,
    setPickerKeyword,
    setPickerOpen,
    setSelectedStoreId,
    storeOptions,
    submitDrawer,
    submitPicker,
    togglePickerProduct,
  };
}
