import type { MemberTabKey, MemberTierEditorForm } from '../types';

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

/**
 * 文件职责：会员管理页面状态与动作编排。
 */
import { computed, onActivated, onMounted, reactive, ref, watch } from 'vue';

import { useAccessStore } from '@vben/stores';

import {
  createDefaultFilters,
  DEFAULT_MEMBER_DAY_SETTING,
  DEFAULT_MEMBER_STATS,
  MEMBER_MANAGE_PERMISSION,
  MEMBER_VIEW_PERMISSION,
} from './member-page/constants';
import { createCouponActions } from './member-page/coupon-actions';
import { createDataActions } from './member-page/data-actions';
import { createDetailActions } from './member-page/detail-actions';
import { createExportActions } from './member-page/export-actions';
import { createFilterActions } from './member-page/filter-actions';
import { createTierActions } from './member-page/tier-actions';

export function useMemberListPage() {
  const accessStore = useAccessStore();

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

  const activeTab = ref<MemberTabKey>('list');
  const filters = reactive(createDefaultFilters());
  const rows = ref<MemberListItemDto[]>([]);
  const pagination = reactive({
    page: 1,
    pageSize: 10,
    total: 0,
  });

  const stats = reactive({ ...DEFAULT_MEMBER_STATS });
  const isListLoading = ref(false);
  const isExporting = ref(false);

  const detail = ref<MemberDetailDto | null>(null);
  const detailOpen = ref(false);
  const detailLoading = ref(false);
  const tagSaving = ref(false);

  const tiers = ref<MemberTierListItemDto[]>([]);
  const tierLoading = ref(false);

  const daySetting = ref<MemberDaySettingDto | null>({
    ...DEFAULT_MEMBER_DAY_SETTING,
  });
  const daySettingSaving = ref(false);

  const tierForm = ref<MemberTierEditorForm | null>(null);
  const tierEditorOpen = ref(false);
  const tierEditorLoading = ref(false);
  const tierEditorSubmitting = ref(false);

  const couponItems = ref<MemberCouponPickerItemDto[]>([]);
  const couponLoading = ref(false);
  const couponKeyword = ref('');
  const couponModalOpen = ref(false);
  const selectedCouponIds = ref<string[]>([]);
  const couponTarget = ref<'' | 'birthday' | 'monthly'>('');

  const storeOptions = computed(() =>
    stores.value.map((item) => ({
      label: item.name,
      value: item.id,
    })),
  );

  const tierOptions = computed(() => [
    {
      label: '全部等级',
      value: '',
    },
    ...tiers.value.map((item) => ({
      label: item.name,
      value: item.tierId,
    })),
  ]);

  const accessCodeSet = computed(
    () => new Set((accessStore.accessCodes ?? []).map(String)),
  );

  const canView = computed(
    () =>
      accessCodeSet.value.has(MEMBER_VIEW_PERMISSION) ||
      accessCodeSet.value.has(MEMBER_MANAGE_PERMISSION),
  );

  const canManage = computed(() =>
    accessCodeSet.value.has(MEMBER_MANAGE_PERMISSION),
  );

  const {
    loadCouponItems,
    loadListAndStats,
    loadStores,
    loadTierData,
    resetDaySetting,
    resetStats,
  } = createDataActions({
    stores,
    selectedStoreId,
    filters,
    rows,
    pagination,
    stats,
    isStoreLoading,
    isListLoading,
    tiers,
    tierLoading,
    daySetting,
    couponItems,
    couponLoading,
  });

  const { handlePageChange, handleReset, handleSearch, setKeyword, setTierId } =
    createFilterActions({
      filters,
      pagination,
      loadListAndStats,
    });

  const { openDetail, saveTags, setDetailOpen } = createDetailActions({
    canManage,
    detail,
    detailLoading,
    detailOpen,
    selectedStoreId,
    tagSaving,
  });

  const { handleExport } = createExportActions({
    canManage,
    filters,
    isExporting,
    selectedStoreId,
  });

  const {
    deleteTier,
    openCreateTier,
    openEditTier,
    saveDaySetting,
    setTierEditorOpen,
    submitTier,
  } = createTierActions({
    canManage,
    daySetting,
    daySettingSaving,
    loadTierData,
    tierEditorOpen,
    tierEditorLoading,
    tierEditorSubmitting,
    tierForm,
    tiers,
  });

  const {
    applyCoupons,
    openCouponPicker,
    resolveCouponLabelMap,
    searchCoupons,
    setCouponKeyword,
    setCouponModalOpen,
    toggleCoupon,
  } = createCouponActions({
    couponItems,
    couponKeyword,
    couponModalOpen,
    couponTarget,
    loadCouponItems,
    selectedCouponIds,
    tierForm,
  });

  const couponLabelMap = computed(() => resolveCouponLabelMap());

  const couponModalTitle = computed(() =>
    couponTarget.value === 'birthday' ? '选择生日赠券' : '选择每月赠券',
  );

  function clearPageDataByPermission() {
    stores.value = [];
    selectedStoreId.value = '';
    rows.value = [];
    pagination.total = 0;
    detail.value = null;
    detailOpen.value = false;
    tiers.value = [];
    couponItems.value = [];
    resetStats();
    resetDaySetting();
  }

  async function bootstrapPageData() {
    await Promise.all([loadStores(), loadTierData()]);
  }

  function setActiveTab(value: MemberTabKey) {
    activeTab.value = value;
  }

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

  async function handleOpenCreateTier() {
    await openCreateTier();
    await loadCouponItems('');
  }

  async function handleOpenEditTier(tierId: string) {
    await openEditTier(tierId);
    await loadCouponItems('');
  }

  async function handleDeleteTier(tierId: string) {
    await deleteTier(tierId);
  }

  async function handleSaveDaySetting(payload: MemberDaySettingDto) {
    await saveDaySetting(payload);
  }

  async function handleSubmitTier(form: MemberTierEditorForm) {
    await submitTier(form);
  }

  function handleOpenCouponPicker(
    target: 'birthday' | 'monthly',
    selectedIds: string[],
  ) {
    void openCouponPicker(target, selectedIds);
  }

  watch(selectedStoreId, async (storeId) => {
    if (!storeId) {
      rows.value = [];
      pagination.total = 0;
      detail.value = null;
      detailOpen.value = false;
      resetStats();
      return;
    }

    pagination.page = 1;
    await loadListAndStats();
  });

  watch(activeTab, async (tab) => {
    if (!canView.value) {
      return;
    }

    if (tab === 'tiers' && tiers.value.length === 0) {
      await loadTierData();
    }
  });

  watch(canView, async (value, oldValue) => {
    if (value === oldValue) {
      return;
    }

    if (!value) {
      clearPageDataByPermission();
      return;
    }

    await bootstrapPageData();
  });

  onMounted(async () => {
    if (!canView.value) {
      clearPageDataByPermission();
      return;
    }

    await bootstrapPageData();
  });

  onActivated(() => {
    if (!canView.value) {
      return;
    }

    if (stores.value.length === 0) {
      void loadStores();
    }

    if (tiers.value.length === 0) {
      void loadTierData();
    }
  });

  return {
    activeTab,
    applyCoupons,
    canManage,
    canView,
    couponItems,
    couponKeyword,
    couponLabelMap,
    couponLoading,
    couponModalOpen,
    couponModalTitle,
    daySetting,
    daySettingSaving,
    detail,
    detailLoading,
    detailOpen,
    filters,
    handleDeleteTier,
    handleExport,
    handleOpenCouponPicker,
    handleOpenCreateTier,
    handleOpenEditTier,
    handlePageChange,
    handleReset,
    handleSaveDaySetting,
    handleSearch,
    handleSubmitTier,
    isExporting,
    isListLoading,
    isStoreLoading,
    openDetail,
    pagination,
    rows,
    saveTags,
    searchCoupons,
    selectedCouponIds,
    selectedStoreId,
    setActiveTab,
    setCouponKeyword,
    setCouponModalOpen,
    setDetailOpen,
    setKeyword,
    setSelectedStoreId,
    setTierEditorOpen,
    setTierId,
    stats,
    storeOptions,
    tagSaving,
    tierEditorLoading,
    tierEditorOpen,
    tierEditorSubmitting,
    tierForm,
    tierLoading,
    tierOptions,
    tiers,
    toggleCoupon,
    resetDaySetting,
  };
}
