import type { MemberFilterState, MemberPaginationState } from '../../types';

import type {
  MemberCouponPickerItemDto,
  MemberDaySettingDto,
  MemberListItemDto,
  MemberListStatsDto,
  MemberTierListItemDto,
} from '#/api/member';
import type { StoreListItemDto } from '#/api/store';

import {
  getMemberCouponPickerApi,
  getMemberDaySettingApi,
  getMemberListApi,
  getMemberListStatsApi,
  getMemberTierListApi,
} from '#/api/member';
import { getStoreListApi } from '#/api/store';

import { DEFAULT_MEMBER_DAY_SETTING, DEFAULT_MEMBER_STATS } from './constants';
import { buildFilterPayload, buildQueryPayload } from './helpers';

interface DataActionOptions {
  couponItems: { value: MemberCouponPickerItemDto[] };
  couponLoading: { value: boolean };
  daySetting: { value: MemberDaySettingDto | null };
  filters: MemberFilterState;
  isListLoading: { value: boolean };
  isStoreLoading: { value: boolean };
  pageSizeMax?: number;
  pagination: MemberPaginationState;
  rows: { value: MemberListItemDto[] };
  selectedStoreId: { value: string };
  stats: MemberListStatsDto;
  stores: { value: StoreListItemDto[] };
  tierLoading: { value: boolean };
  tiers: { value: MemberTierListItemDto[] };
}

/**
 * 文件职责：会员页基础数据加载动作。
 */
export function createDataActions(options: DataActionOptions) {
  function resetStats() {
    options.stats.totalMembers = DEFAULT_MEMBER_STATS.totalMembers;
    options.stats.monthlyNewMembers = DEFAULT_MEMBER_STATS.monthlyNewMembers;
    options.stats.activeMembers = DEFAULT_MEMBER_STATS.activeMembers;
    options.stats.dormantMembers = DEFAULT_MEMBER_STATS.dormantMembers;
  }

  async function loadStores() {
    options.isStoreLoading.value = true;
    try {
      const result = await getStoreListApi({ page: 1, pageSize: 200 });
      options.stores.value = result.items;

      if (result.items.length === 0) {
        options.selectedStoreId.value = '';
        options.rows.value = [];
        options.pagination.total = 0;
        resetStats();
        return;
      }

      const matched = result.items.some(
        (item) => item.id === options.selectedStoreId.value,
      );
      if (!matched) {
        options.selectedStoreId.value = result.items[0]?.id ?? '';
      }
    } finally {
      options.isStoreLoading.value = false;
    }
  }

  async function loadListAndStats() {
    if (!options.selectedStoreId.value) {
      options.rows.value = [];
      options.pagination.total = 0;
      resetStats();
      return;
    }

    options.isListLoading.value = true;
    try {
      const [listResult, statsResult] = await Promise.all([
        getMemberListApi(
          buildQueryPayload(
            options.selectedStoreId.value,
            options.filters,
            options.pagination.page,
            options.pagination.pageSize,
          ),
        ),
        getMemberListStatsApi(
          buildFilterPayload(options.selectedStoreId.value, options.filters),
        ),
      ]);

      options.rows.value = listResult.items;
      options.pagination.total = listResult.total;
      options.pagination.page = listResult.page;
      options.pagination.pageSize = listResult.pageSize;

      options.stats.totalMembers = statsResult.totalMembers;
      options.stats.monthlyNewMembers = statsResult.monthlyNewMembers;
      options.stats.activeMembers = statsResult.activeMembers;
      options.stats.dormantMembers = statsResult.dormantMembers;
    } finally {
      options.isListLoading.value = false;
    }
  }

  async function loadTierData() {
    options.tierLoading.value = true;
    try {
      const [tierResult, daySettingResult] = await Promise.all([
        getMemberTierListApi(),
        getMemberDaySettingApi(),
      ]);

      options.tiers.value = tierResult;
      options.daySetting.value = daySettingResult;
    } finally {
      options.tierLoading.value = false;
    }
  }

  async function loadCouponItems(keyword: string) {
    if (!options.selectedStoreId.value) {
      options.couponItems.value = [];
      return;
    }

    options.couponLoading.value = true;
    try {
      options.couponItems.value = await getMemberCouponPickerApi({
        storeId: options.selectedStoreId.value,
        keyword: keyword.trim() || undefined,
      });
    } finally {
      options.couponLoading.value = false;
    }
  }

  function resetDaySetting() {
    options.daySetting.value = { ...DEFAULT_MEMBER_DAY_SETTING };
  }

  return {
    loadCouponItems,
    loadListAndStats,
    loadStores,
    loadTierData,
    resetDaySetting,
    resetStats,
  };
}
