import type { StoreListItemDto } from '#/api/store';
import type {
  FlashSaleCardViewModel,
  FlashSalePickerCategoryItem,
  FlashSalePickerProductItem,
  FlashSaleStatsViewModel,
} from '#/views/marketing/flash-sale/types';

/**
 * 文件职责：限时折扣页面状态与行为编排。
 */
import { computed, onMounted, reactive, ref, watch } from 'vue';

import { createCardActions } from './flash-sale-page/card-actions';
import {
  createDefaultFlashSaleEditorForm,
  createDefaultFlashSaleFilterForm,
  FLASH_SALE_STATUS_FILTER_OPTIONS,
} from './flash-sale-page/constants';
import {
  createDataActions,
  createEmptyStats,
} from './flash-sale-page/data-actions';
import { createDrawerActions } from './flash-sale-page/drawer-actions';
import { createPickerActions } from './flash-sale-page/picker-actions';

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

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

  const rows = ref<FlashSaleCardViewModel[]>([]);
  const stats = ref<FlashSaleStatsViewModel>(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(createDefaultFlashSaleEditorForm());

  const isPickerOpen = ref(false);
  const isPickerLoading = ref(false);
  const pickerKeyword = ref('');
  const pickerCategoryFilterId = ref('');
  const pickerSelectedProductIds = ref<string[]>([]);
  const pickerCategories = ref<FlashSalePickerCategoryItem[]>([]);
  const pickerProducts = ref<FlashSalePickerProductItem[]>([]);

  const storeOptions = computed(() => [
    { label: '全部门店', value: '' },
    ...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,
    setPickerCategoryFilterId,
    setPickerKeyword,
    setPickerOpen,
    setPickerSelectedProductIds,
    submitPicker,
    toggleAllProducts,
    togglePickerProduct,
  } = createPickerActions({
    isPickerLoading,
    isPickerOpen,
    pickerCategories,
    pickerCategoryFilterId,
    pickerKeyword,
    pickerProducts,
    pickerSelectedProductIds,
  });

  const {
    drawerMode,
    openCreateDrawer,
    openEditDrawer,
    openProductPicker,
    quickSelectWeekDays,
    removeProduct,
    setDrawerOpen,
    setFormChannels,
    setFormCycleType,
    setFormName,
    setFormPerUserLimit,
    setFormRecurringDateMode,
    setFormTimeRange,
    setFormValidDateRange,
    setProductDiscountPrice,
    setProductPerUserLimit,
    submitDrawer,
    toggleChannel,
    toggleWeekDay,
  } = createDrawerActions({
    form,
    isDrawerLoading,
    isDrawerOpen,
    isDrawerSubmitting,
    loadActivities,
    openPicker,
    resolveOperationStoreId,
    selectedStoreId,
    stores,
  });

  const { removeActivity, toggleActivityStatus } = 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: '' | FlashSaleCardViewModel['displayStatus'],
  ) {
    filterForm.status = value;
  }

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

  async function resetFilters() {
    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 handlePickerSearch() {
    await reloadPickerList();
  }

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

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

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

  return {
    applyFilters,
    drawerSubmitText,
    drawerTitle,
    filterForm,
    form,
    FLASH_SALE_STATUS_FILTER_OPTIONS,
    handlePageChange,
    handlePickerCategoryFilterChange,
    handlePickerSearch,
    hasStore,
    isDrawerLoading,
    isDrawerOpen,
    isDrawerSubmitting,
    isLoading,
    isPickerLoading,
    isPickerOpen,
    isStoreLoading,
    keyword,
    openCreateDrawer,
    openEditDrawer,
    openProductPicker,
    page,
    pageSize,
    pickerCategories,
    pickerCategoryFilterId,
    pickerKeyword,
    pickerProducts,
    pickerSelectedProductIds,
    quickSelectWeekDays,
    reloadPickerList,
    removeActivity,
    removeProduct,
    resetFilters,
    rows,
    selectedStoreId,
    setDrawerOpen,
    setFormChannels,
    setFormCycleType,
    setFormName,
    setFormPerUserLimit,
    setFormRecurringDateMode,
    setFormTimeRange,
    setFormValidDateRange,
    setKeyword: setKeywordValue,
    setPickerKeyword,
    setPickerOpen,
    setPickerSelectedProductIds,
    setProductDiscountPrice,
    setProductPerUserLimit,
    setSelectedStoreId,
    setStatusFilter,
    stats,
    storeNameMap,
    storeOptions,
    submitDrawer,
    submitPicker,
    toggleActivityStatus,
    toggleAllProducts,
    toggleChannel,
    togglePickerProduct,
    toggleWeekDay,
    total,
  };
}
