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

/**
 * 文件职责：满减活动页面状态与行为编排。
 * 1. 管理门店、筛选、分页、统计与加载状态。
 * 2. 编排主抽屉编辑与二级范围抽屉选择。
 * 3. 封装卡片停用/删除动作。
 */
import { computed, onMounted, reactive, ref, watch } from 'vue';

import { createCardActions } from './full-reduction-page/card-actions';
import {
  createDefaultFullReductionEditorForm,
  createDefaultFullReductionFilterForm,
  createDefaultScopeForm,
  FULL_REDUCTION_ACTIVITY_FILTER_OPTIONS,
  FULL_REDUCTION_STATUS_FILTER_OPTIONS,
} from './full-reduction-page/constants';
import {
  createDataActions,
  createEmptyStats,
} from './full-reduction-page/data-actions';
import { createDrawerActions } from './full-reduction-page/drawer-actions';
import { createPickerActions } from './full-reduction-page/picker-actions';

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

  const filterForm = reactive(createDefaultFullReductionFilterForm());
  const keyword = ref('');

  const rows = ref<FullReductionCardViewModel[]>([]);
  const stats = ref<FullReductionStatsViewModel>(createEmptyStats());
  const page = ref(1);
  const pageSize = ref(4);
  const total = ref(0);
  const isLoading = ref(false);

  const isDrawerOpen = ref(false);
  const isDrawerLoading = ref(false);
  const isDrawerSubmitting = ref(false);
  const form = reactive(createDefaultFullReductionEditorForm());

  const isPickerOpen = ref(false);
  const isPickerLoading = ref(false);
  const pickerTitle = ref('选择商品范围');
  const pickerTarget = ref<FullReductionPickerTarget>('giftApplicable');
  const pickerAllowAll = ref(true);
  const pickerScope = ref<FullReductionScopeForm>(
    createDefaultScopeForm('all'),
  );
  const pickerKeyword = ref('');
  const pickerCategoryFilterId = ref('');
  const pickerCategories = ref<FullReductionPickerCategoryItem[]>([]);
  const pickerProducts = ref<FullReductionPickerProductItem[]>([]);

  const storeOptions = computed(() => [
    { label: '全部门店', value: '' },
    ...stores.value.map((item) => ({
      label: item.name,
      value: item.id,
    })),
  ]);
  const scopedStoreOptions = computed(() =>
    stores.value.map((item) => ({
      label: item.name,
      value: item.id,
    })),
  );
  const storeNameMap = computed<Record<string, string>>(() =>
    Object.fromEntries(stores.value.map((item) => [item.id, item.name])),
  );

  const hasStore = computed(() => stores.value.length > 0);

  function resolveOperationStoreId(preferredStoreIds: string[] = []) {
    if (selectedStoreId.value) {
      return selectedStoreId.value;
    }

    for (const storeId of preferredStoreIds) {
      if (stores.value.some((item) => item.id === storeId)) {
        return storeId;
      }
    }

    if (preferredStoreIds.length > 0) {
      return preferredStoreIds[0] ?? '';
    }

    return stores.value[0]?.id ?? '';
  }

  const { loadActivities, loadStores } = createDataActions({
    stores,
    selectedStoreId,
    isStoreLoading,
    filterForm,
    keyword,
    rows,
    stats,
    isLoading,
    page,
    pageSize,
    total,
  });

  const {
    openPicker,
    reloadPickerList,
    searchPickerProducts,
    setPickerCategoryFilterId,
    setPickerCategoryIds,
    setPickerKeyword,
    setPickerOpen,
    setPickerProductIds,
    setPickerScopeType,
    submitPicker,
  } = createPickerActions({
    isPickerLoading,
    isPickerOpen,
    pickerAllowAll,
    pickerCategories,
    pickerCategoryFilterId,
    pickerKeyword,
    pickerProducts,
    pickerScope,
    pickerTarget,
    pickerTitle,
    resolveOperationStoreId,
  });

  const {
    addReduceTier,
    drawerMode,
    openCreateDrawer,
    openEditDrawer,
    openGiftApplicablePicker,
    openGiftScopePicker,
    openSecondHalfApplicablePicker,
    removeReduceTier,
    setDrawerOpen,
    setFormActivityType,
    setFormChannels,
    setFormDescription,
    setFormName,
    setFormStackWithCoupon,
    setFormStoreIds,
    setFormStoreScopeMode,
    setFormValidDateRange,
    setGiftBuyQuantity,
    setGiftGiftQuantity,
    setGiftScopeType,
    setReduceTierMeetAmount,
    setReduceTierReduceAmount,
    setSecondHalfDiscountType,
    submitDrawer,
  } = createDrawerActions({
    form,
    isDrawerLoading,
    isDrawerOpen,
    isDrawerSubmitting,
    loadActivities,
    openPicker,
    resolveOperationStoreId,
    selectedStoreId,
    stores,
  });

  const { disableActivity, removeActivity } = createCardActions({
    loadActivities,
    resolveOperationStoreId,
  });

  const drawerTitle = computed(() =>
    drawerMode.value === 'create' ? '创建活动' : '编辑活动',
  );
  const drawerSubmitText = computed(() => '保存');

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

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

  function setStatusFilter(
    value: '' | FullReductionCardViewModel['displayStatus'],
  ) {
    filterForm.status = value;
  }

  function setActivityTypeFilter(
    value: '' | FullReductionCardViewModel['activityType'],
  ) {
    filterForm.activityType = value;
  }

  async function applyFilters() {
    page.value = 1;
    await loadActivities();
  }

  async function resetFilters() {
    filterForm.activityType = '';
    filterForm.status = '';
    keyword.value = '';
    page.value = 1;
    await loadActivities();
  }

  async function handlePageChange(nextPage: number, nextPageSize: number) {
    page.value = nextPage;
    pageSize.value = nextPageSize;
    await loadActivities();
  }

  async function handlePickerScopeTypeChange(
    value: FullReductionScopeForm['scopeType'],
  ) {
    setPickerScopeType(value);
    if (value === 'product') {
      await searchPickerProducts();
      return;
    }
    await reloadPickerList();
  }

  async function handlePickerCategoryFilterChange(value: string) {
    setPickerCategoryFilterId(value);
    await searchPickerProducts();
  }

  async function handlePickerSearch() {
    await searchPickerProducts();
  }

  watch(selectedStoreId, () => {
    page.value = 1;
    filterForm.activityType = '';
    filterForm.status = '';
    keyword.value = '';
    void loadActivities();
  });

  onMounted(async () => {
    await loadStores();
    await loadActivities();
  });

  return {
    addReduceTier,
    applyFilters,
    disableActivity,
    drawerSubmitText,
    drawerTitle,
    filterForm,
    form,
    FULL_REDUCTION_ACTIVITY_FILTER_OPTIONS,
    FULL_REDUCTION_STATUS_FILTER_OPTIONS,
    handlePageChange,
    handlePickerCategoryFilterChange,
    handlePickerScopeTypeChange,
    handlePickerSearch,
    hasStore,
    isDrawerLoading,
    isDrawerOpen,
    isDrawerSubmitting,
    isLoading,
    isPickerLoading,
    isPickerOpen,
    isStoreLoading,
    keyword,
    openCreateDrawer,
    openEditDrawer,
    openGiftApplicablePicker,
    openGiftScopePicker,
    openSecondHalfApplicablePicker,
    page,
    pageSize,
    pickerAllowAll,
    pickerCategories,
    pickerCategoryFilterId,
    pickerKeyword,
    pickerProducts,
    pickerScope,
    pickerTarget,
    pickerTitle,
    removeActivity,
    removeReduceTier,
    resetFilters,
    rows,
    scopedStoreOptions,
    selectedStoreId,
    setDrawerOpen,
    setFormActivityType,
    setFormChannels,
    setFormDescription,
    setFormName,
    setFormStackWithCoupon,
    setFormStoreIds,
    setFormStoreScopeMode,
    setFormValidDateRange,
    setGiftBuyQuantity,
    setGiftGiftQuantity,
    setGiftScopeType,
    setKeyword: setKeywordValue,
    setPickerCategoryIds,
    setPickerKeyword,
    setPickerOpen,
    setPickerProductIds,
    setReduceTierMeetAmount,
    setReduceTierReduceAmount,
    setSecondHalfDiscountType,
    setSelectedStoreId,
    setStatusFilter,
    setTypeFilter: setActivityTypeFilter,
    stats,
    storeNameMap,
    storeOptions,
    stores,
    submitDrawer,
    submitPicker,
    total,
  };
}
