import type {
  CustomerDetailDto,
  CustomerListItemDto,
  CustomerProfileDto,
} from '#/api/customer';
import type { StoreListItemDto } from '#/api/store';

/**
 * 文件职责：客户列表页面状态与动作编排。
 */
import { computed, onActivated, onMounted, reactive, ref, watch } from 'vue';
import { useRouter } from 'vue-router';

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

import {
  createDefaultFilters,
  CUSTOMER_LIST_MANAGE_PERMISSION,
  DEFAULT_STATS,
} from './customer-list-page/constants';
import { createDataActions } from './customer-list-page/data-actions';
import { createDrawerActions } from './customer-list-page/drawer-actions';
import { createExportActions } from './customer-list-page/export-actions';
import { createFilterActions } from './customer-list-page/filter-actions';
import { createNavigationActions } from './customer-list-page/navigation-actions';

export function useCustomerListPage() {
  const accessStore = useAccessStore();
  const router = useRouter();

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

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

  const stats = reactive({ ...DEFAULT_STATS });
  const isListLoading = ref(false);
  const isStatsLoading = ref(false);

  const detail = ref<CustomerDetailDto | null>(null);
  const isDetailDrawerOpen = ref(false);
  const isDetailLoading = ref(false);

  const profile = ref<CustomerProfileDto | null>(null);
  const isProfileDrawerOpen = ref(false);
  const isProfileLoading = ref(false);

  const isExporting = ref(false);

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

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

  const { loadPageData, loadStores, resetStats } = createDataActions({
    stores,
    selectedStoreId,
    filters,
    rows,
    pagination,
    stats,
    isStoreLoading,
    isListLoading,
    isStatsLoading,
  });

  const {
    handlePageChange,
    handleReset,
    handleSearch,
    setKeyword,
    setOrderCountRange,
    setRegisterPeriod,
    setTag,
  } = createFilterActions({
    filters,
    pagination,
    loadPageData,
  });

  const { openDetail, openProfile, setDetailDrawerOpen, setProfileDrawerOpen } =
    createDrawerActions({
      selectedStoreId,
      detail,
      isDetailDrawerOpen,
      isDetailLoading,
      profile,
      isProfileDrawerOpen,
      isProfileLoading,
    });

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

  const { openProfilePage } = createNavigationActions({
    selectedStoreId,
    router,
  });

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

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

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

  onMounted(() => {
    void loadStores();
  });

  onActivated(() => {
    if (stores.value.length === 0 || !selectedStoreId.value) {
      void loadStores();
    }
  });

  return {
    canManage,
    detail,
    filters,
    handleExport,
    handlePageChange,
    handleReset,
    handleSearch,
    isDetailDrawerOpen,
    isDetailLoading,
    isExporting,
    isListLoading,
    isProfileDrawerOpen,
    isProfileLoading,
    isStatsLoading,
    isStoreLoading,
    openDetail,
    openProfile,
    openProfilePage,
    pagination,
    profile,
    rows,
    selectedStoreId,
    setDetailDrawerOpen,
    setKeyword,
    setOrderCountRange,
    setProfileDrawerOpen,
    setRegisterPeriod,
    setSelectedStoreId,
    setTag,
    stats,
    storeOptions,
  };
}
