import type { StoreListItemDto } from '#/api/store';
import type {
  SeckillCardViewModel,
  SeckillPickerCategoryItem,
  SeckillPickerProductItem,
  SeckillStatsViewModel,
} from '#/views/marketing/seckill/types';

/**
 * 文件职责：秒杀活动页面状态与行为编排。
 */
import { computed, onMounted, reactive, ref, watch } from 'vue';

import { createCardActions } from './seckill-page/card-actions';
import {
  createDefaultSeckillEditorForm,
  createDefaultSeckillFilterForm,
  SECKILL_STATUS_FILTER_OPTIONS,
} from './seckill-page/constants';
import {
  createDataActions,
  createEmptyStats,
} from './seckill-page/data-actions';
import { createDrawerActions } from './seckill-page/drawer-actions';
import { createPickerActions } from './seckill-page/picker-actions';

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

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

  const rows = ref<SeckillCardViewModel[]>([]);
  const stats = ref<SeckillStatsViewModel>(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(createDefaultSeckillEditorForm());

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

  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 {
    addSession,
    drawerMode,
    openCreateDrawer,
    openEditDrawer,
    openProductPicker,
    removeProduct,
    removeSession,
    setActivityType,
    setDrawerOpen,
    setFormChannels,
    setFormName,
    setFormPerUserLimit,
    setFormTimeRange,
    setFormValidDateRange,
    setPreheatEnabled,
    setPreheatHours,
    setProductPerUserLimit,
    setProductSeckillPrice,
    setProductStockLimit,
    setSessionDuration,
    setSessionStartTime,
    submitDrawer,
    toggleChannel,
  } = 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: '' | SeckillCardViewModel['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 {
    addSession,
    applyFilters,
    drawerSubmitText,
    drawerTitle,
    filterForm,
    form,
    SECKILL_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,
    reloadPickerList,
    removeActivity,
    removeProduct,
    removeSession,
    resetFilters,
    rows,
    selectedStoreId,
    setActivityType,
    setDrawerOpen,
    setFormChannels,
    setFormName,
    setFormPerUserLimit,
    setFormTimeRange,
    setFormValidDateRange,
    setKeyword: setKeywordValue,
    setPickerKeyword,
    setPickerOpen,
    setPickerSelectedProductIds,
    setPreheatEnabled,
    setPreheatHours,
    setProductPerUserLimit,
    setProductSeckillPrice,
    setProductStockLimit,
    setSelectedStoreId,
    setSessionDuration,
    setSessionStartTime,
    setStatusFilter,
    stats,
    storeNameMap,
    storeOptions,
    submitDrawer,
    submitPicker,
    toggleActivityStatus,
    toggleAllProducts,
    toggleChannel,
    togglePickerProduct,
    total,
  };
}
