import type { Ref } from 'vue';

import type { StoreListItemDto } from '#/api/store';
import type {
  PointMallProductCardViewModel,
  PointMallProductFilterForm,
  PointMallRecordFilterForm,
  PointMallRecordPager,
  PointMallRecordStatsViewModel,
  PointMallRuleForm,
  PointMallRuleStatsViewModel,
} from '#/views/member/points-mall/types';

import { message } from 'ant-design-vue';

import {
  getMemberPointMallProductListApi,
  getMemberPointMallRecordListApi,
  getMemberPointMallRuleDetailApi,
} from '#/api/member/points-mall';
import { getStoreListApi } from '#/api/store';

import { mapRecordFilterToQuery, mapRuleToForm } from './helpers';

interface CreateDataActionsOptions {
  isProductLoading: Ref<boolean>;
  isRecordLoading: Ref<boolean>;
  isRuleLoading: Ref<boolean>;
  isStoreLoading: Ref<boolean>;
  productFilterForm: PointMallProductFilterForm;
  productRows: Ref<PointMallProductCardViewModel[]>;
  recordFilterForm: PointMallRecordFilterForm;
  recordPager: Ref<PointMallRecordPager>;
  recordStats: Ref<PointMallRecordStatsViewModel>;
  ruleForm: PointMallRuleForm;
  ruleStats: Ref<PointMallRuleStatsViewModel>;
  selectedStoreId: Ref<string>;
  stores: Ref<StoreListItemDto[]>;
}

export function createDataActions(options: CreateDataActionsOptions) {
  function resetRuleData() {
    options.ruleStats.value = {
      totalIssuedPoints: 0,
      redeemedPoints: 0,
      pointMembers: 0,
      redeemRate: 0,
    };
  }

  function resetProductData() {
    options.productRows.value = [];
  }

  function resetRecordData() {
    options.recordPager.value = {
      ...options.recordPager.value,
      items: [],
      totalCount: 0,
    };
    options.recordStats.value = {
      todayRedeemCount: 0,
      pendingPhysicalCount: 0,
      currentMonthUsedPoints: 0,
    };
  }

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

      options.stores.value = result.items ?? [];

      if (options.stores.value.length === 0) {
        options.selectedStoreId.value = '';
        resetRuleData();
        resetProductData();
        resetRecordData();
        return;
      }

      if (!options.selectedStoreId.value) {
        options.selectedStoreId.value = options.stores.value[0]?.id ?? '';
        return;
      }

      const exists = options.stores.value.some(
        (item) => item.id === options.selectedStoreId.value,
      );
      if (!exists) {
        options.selectedStoreId.value = options.stores.value[0]?.id ?? '';
      }
    } catch (error) {
      console.error(error);
      message.error('加载门店失败');
    } finally {
      options.isStoreLoading.value = false;
    }
  }

  async function loadRuleDetail() {
    if (!options.selectedStoreId.value) {
      resetRuleData();
      return;
    }

    options.isRuleLoading.value = true;
    try {
      const result = await getMemberPointMallRuleDetailApi({
        storeId: options.selectedStoreId.value,
      });

      const form = mapRuleToForm({
        ...result.rule,
        storeId: options.selectedStoreId.value,
      });
      options.ruleForm.isConsumeRewardEnabled = form.isConsumeRewardEnabled;
      options.ruleForm.consumeAmountPerStep = form.consumeAmountPerStep;
      options.ruleForm.consumeRewardPointsPerStep =
        form.consumeRewardPointsPerStep;
      options.ruleForm.isReviewRewardEnabled = form.isReviewRewardEnabled;
      options.ruleForm.reviewRewardPoints = form.reviewRewardPoints;
      options.ruleForm.isRegisterRewardEnabled = form.isRegisterRewardEnabled;
      options.ruleForm.registerRewardPoints = form.registerRewardPoints;
      options.ruleForm.isSigninRewardEnabled = form.isSigninRewardEnabled;
      options.ruleForm.signinRewardPoints = form.signinRewardPoints;
      options.ruleForm.expiryMode = form.expiryMode;
      options.ruleStats.value = result.stats ?? options.ruleStats.value;
    } catch (error) {
      console.error(error);
      resetRuleData();
      message.error('加载积分规则失败');
    } finally {
      options.isRuleLoading.value = false;
    }
  }

  async function loadProductList() {
    if (!options.selectedStoreId.value) {
      resetProductData();
      return;
    }

    options.isProductLoading.value = true;
    try {
      const result = await getMemberPointMallProductListApi({
        storeId: options.selectedStoreId.value,
        status: options.productFilterForm.status || undefined,
        keyword: options.productFilterForm.keyword.trim() || undefined,
      });
      options.productRows.value = result.items ?? [];
    } catch (error) {
      console.error(error);
      resetProductData();
      message.error('加载兑换商品失败');
    } finally {
      options.isProductLoading.value = false;
    }
  }

  async function loadRecordList() {
    if (!options.selectedStoreId.value) {
      resetRecordData();
      return;
    }

    options.isRecordLoading.value = true;
    try {
      const query = mapRecordFilterToQuery(options.recordFilterForm);
      const result = await getMemberPointMallRecordListApi({
        storeId: options.selectedStoreId.value,
        page: options.recordPager.value.page,
        pageSize: options.recordPager.value.pageSize,
        ...query,
      });

      options.recordPager.value = {
        items: result.items ?? [],
        page: result.page,
        pageSize: result.pageSize,
        totalCount: result.totalCount,
      };
      options.recordStats.value = result.stats ?? {
        todayRedeemCount: 0,
        pendingPhysicalCount: 0,
        currentMonthUsedPoints: 0,
      };
    } catch (error) {
      console.error(error);
      resetRecordData();
      message.error('加载兑换记录失败');
    } finally {
      options.isRecordLoading.value = false;
    }
  }

  return {
    loadProductList,
    loadRecordList,
    loadRuleDetail,
    loadStores,
  };
}
