import type { StoreListItemDto } from '#/api/store';
import type { CouponCardViewModel } from '#/views/marketing/coupon/types';

/**
 * 文件职责：优惠券页面状态与行为编排。
 * 1. 管理门店、筛选、分页、统计与加载状态。
 * 2. 编排抽屉编辑动作与卡片启停删除动作。
 */
import { computed, onMounted, reactive, ref, watch } from 'vue';

import { createCardActions } from './coupon-page/card-actions';
import {
  COUPON_STATUS_FILTER_OPTIONS,
  COUPON_TYPE_FILTER_OPTIONS,
  createDefaultCouponEditorForm,
  createDefaultCouponFilterForm,
} from './coupon-page/constants';
import {
  createDataActions,
  createEmptyStats,
} from './coupon-page/data-actions';
import { createDrawerActions } from './coupon-page/drawer-actions';

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

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

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

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

  const storeOptions = 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(() => !!selectedStoreId.value);

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

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

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

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

  function setTypeFilter(value: '' | CouponCardViewModel['couponType']) {
    filterForm.couponType = value;
  }

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

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

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

  const {
    drawerMode,
    openCreateDrawer,
    openEditDrawer,
    setDrawerOpen,
    setFormChannels,
    setFormCouponType,
    setFormMinimumSpend,
    setFormName,
    setFormPerUserLimit,
    setFormRelativeValidDays,
    setFormStoreIds,
    setFormStoreScopeMode,
    setFormTotalQuantity,
    setFormValidDateRange,
    setFormValidityType,
    setFormValue,
    submitDrawer,
  } = createDrawerActions({
    form,
    isDrawerLoading,
    isDrawerOpen,
    isDrawerSubmitting,
    selectedStoreId,
    loadCoupons,
  });

  const { disableCoupon, enableCoupon, removeCoupon } = createCardActions({
    selectedStoreId,
    loadCoupons,
  });

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

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

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

  return {
    applyFilters,
    COUPON_STATUS_FILTER_OPTIONS,
    COUPON_TYPE_FILTER_OPTIONS,
    disableCoupon,
    drawerSubmitText,
    drawerTitle,
    enableCoupon,
    filterForm,
    form,
    handlePageChange,
    hasStore,
    isDrawerLoading,
    isDrawerOpen,
    isDrawerSubmitting,
    isLoading,
    isStoreLoading,
    keyword,
    openCreateDrawer,
    openEditDrawer,
    page,
    pageSize,
    removeCoupon,
    resetFilters,
    rows,
    selectedStoreId,
    setDrawerOpen,
    setFormChannels,
    setFormCouponType,
    setFormMinimumSpend,
    setFormName,
    setFormPerUserLimit,
    setFormRelativeValidDays,
    setFormStoreIds,
    setFormStoreScopeMode,
    setFormTotalQuantity,
    setFormValidDateRange,
    setFormValidityType,
    setFormValue,
    setKeyword,
    setSelectedStoreId,
    setStatusFilter,
    setTypeFilter,
    stats,
    storeNameMap,
    storeOptions,
    stores,
    submitDrawer,
    total,
  };
}
