import type { StoreListItemDto } from '#/api/store';
import type {
  PunchCardPickerCategoryItem,
  PunchCardPickerProductItem,
  PunchCardTabKey,
  PunchCardTemplateCardViewModel,
  PunchCardTemplateOptionViewModel,
  PunchCardUsagePager,
} from '#/views/marketing/punch-card/types';

/**
 * 文件职责：次卡页面状态与行为编排。
 */
import { computed, onMounted, reactive, ref, watch } from 'vue';

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

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

import { exportMarketingPunchCardUsageRecordApi } from '#/api/marketing';
import {
  getProductCategoryListApi,
  getProductLabelListApi,
} from '#/api/product';

import { createDefaultPunchCardUsagePager } from '../types';
import { createCardActions } from './punch-card-page/card-actions';
import {
  createDefaultPunchCardEditorForm,
  createDefaultPunchCardListFilterForm,
  createDefaultPunchCardUsageFilterForm,
  createDefaultPunchCardUsageStats,
  PUNCH_CARD_MANAGE_PERMISSION,
} from './punch-card-page/constants';
import { createDataActions } from './punch-card-page/data-actions';
import { createDrawerActions } from './punch-card-page/drawer-actions';
import { downloadBase64File } from './punch-card-page/helpers';
import { createPickerActions } from './punch-card-page/picker-actions';

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

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

  const activeTab = ref<PunchCardTabKey>('list');

  const listFilterForm = reactive(createDefaultPunchCardListFilterForm());
  const listKeyword = ref('');
  const listPage = ref(1);
  const listPageSize = ref(4);
  const listRows = ref<PunchCardTemplateCardViewModel[]>([]);
  const listTotalCount = ref(0);
  const listStats = ref({
    onSaleCount: 0,
    totalSoldCount: 0,
    totalRevenueAmount: 0,
    activeInUseCount: 0,
  });
  const isListLoading = ref(false);

  const recordFilterForm = reactive(createDefaultPunchCardUsageFilterForm());
  const recordKeyword = ref('');
  const usagePager = ref<PunchCardUsagePager>(
    createDefaultPunchCardUsagePager(),
  );
  const usageStats = ref(createDefaultPunchCardUsageStats());
  const templateOptions = ref<PunchCardTemplateOptionViewModel[]>([]);
  const isRecordLoading = ref(false);

  const isDrawerOpen = ref(false);
  const isDrawerLoading = ref(false);
  const isDrawerSubmitting = ref(false);
  const drawerMode = ref<'create' | 'edit'>('create');
  const form = reactive(createDefaultPunchCardEditorForm());

  const isPickerOpen = ref(false);
  const isPickerLoading = ref(false);
  const pickerKeyword = ref('');
  const pickerCategoryFilterId = ref('');
  const pickerCategories = ref<PunchCardPickerCategoryItem[]>([]);
  const pickerProducts = ref<PunchCardPickerProductItem[]>([]);
  const pickerSelectedProductIds = ref<string[]>([]);
  const scopeCategoryOptions = ref<Array<{ label: string; value: string }>>([]);
  const scopeTagOptions = ref<Array<{ label: string; value: string }>>([]);

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

  const hasStore = computed(() => stores.value.length > 0);

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

  const pickerCategoryOptions = computed(() => [
    { label: '全部分类', value: '' },
    ...pickerCategories.value.map((item) => ({
      label: item.name,
      value: item.id,
    })),
  ]);

  const drawerTitle = computed(() =>
    drawerMode.value === 'create' ? '创建次卡' : '编辑次卡',
  );

  const drawerSubmitText = computed(() => '保存');

  function resolveStoreId() {
    return selectedStoreId.value;
  }

  const { loadStores, loadPunchCardList, loadUsageRecords } = createDataActions(
    {
      stores,
      selectedStoreId,
      isStoreLoading,
      isListLoading,
      listFilterForm,
      listKeyword,
      listPage,
      listPageSize,
      listRows,
      listStats,
      listTotalCount,
      isRecordLoading,
      recordFilterForm,
      recordKeyword,
      usagePager,
      usageStats,
      templateOptions,
    },
  );

  const {
    openProductPicker,
    reloadPickerData,
    searchPickerProducts,
    setPickerCategoryFilterId,
    setPickerKeyword,
    setPickerOpen,
    setPickerSelectedProductIds,
    submitPicker,
    togglePickerProduct,
  } = createPickerActions({
    isPickerLoading,
    isPickerOpen,
    pickerCategories,
    pickerCategoryFilterId,
    pickerKeyword,
    pickerProducts,
    pickerSelectedProductIds,
    resolveStoreId,
  });

  const {
    openCreateDrawer,
    openEditDrawer,
    openScopeProductPicker,
    setDrawerOpen,
    setFormAllowTransfer,
    setFormCoverImageUrl,
    setFormDailyLimit,
    setFormDescription,
    setFormExpireStrategy,
    setFormName,
    setFormOriginalPrice,
    setFormPerOrderLimit,
    setFormPerUserPurchaseLimit,
    setFormSalePrice,
    setFormScopeType,
    setFormTotalTimes,
    setFormUsageCapAmount,
    setFormUsageMode,
    setFormValidDateRange,
    setFormValidityDays,
    setFormValidityType,
    setScopeCategoryIds,
    setScopeProductIds,
    setScopeTagIds,
    submitDrawer,
    toggleNotifyChannel,
  } = createDrawerActions({
    canManage,
    form,
    drawerMode,
    isDrawerLoading,
    isDrawerOpen,
    isDrawerSubmitting,
    loadPunchCardList,
    loadUsageRecords,
    selectedStoreId,
    openProductPicker,
  });

  const { removeCard, toggleStatus } = createCardActions({
    canManage,
    selectedStoreId,
    loadPunchCardList,
    loadUsageRecords,
  });

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

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

  function setListKeyword(value: string) {
    listKeyword.value = value;
  }

  function setListStatusFilter(value: '' | 'disabled' | 'enabled') {
    listFilterForm.status = value;
  }

  function setRecordKeyword(value: string) {
    recordKeyword.value = value;
  }

  function setRecordTemplateFilter(value: string) {
    recordFilterForm.templateId = value;
  }

  function setRecordStatusFilter(value: '' | 'expired' | 'normal' | 'used_up') {
    recordFilterForm.status = value;
  }

  async function applyListFilters() {
    listPage.value = 1;
    await loadPunchCardList();
  }

  async function resetListFilters() {
    listFilterForm.status = '';
    listKeyword.value = '';
    listPage.value = 1;
    await loadPunchCardList();
  }

  async function handleListPageChange(page: number, pageSize: number) {
    listPage.value = page;
    listPageSize.value = pageSize;
    await loadPunchCardList();
  }

  async function applyRecordFilters() {
    usagePager.value = {
      ...usagePager.value,
      page: 1,
    };
    await loadUsageRecords();
  }

  async function resetRecordFilters() {
    recordFilterForm.templateId = '';
    recordFilterForm.status = '';
    recordKeyword.value = '';
    usagePager.value = {
      ...usagePager.value,
      page: 1,
    };
    await loadUsageRecords();
  }

  async function handleRecordPageChange(page: number, pageSize: number) {
    usagePager.value = {
      ...usagePager.value,
      page,
      pageSize,
    };
    await loadUsageRecords();
  }

  async function handlePickerCategoryChange(value: string) {
    setPickerCategoryFilterId(value);
    await searchPickerProducts();
  }

  async function handlePickerSearch() {
    await searchPickerProducts();
  }

  async function exportUsageRecords() {
    if (!selectedStoreId.value) {
      message.warning('请先选择门店');
      return;
    }

    try {
      const result = await exportMarketingPunchCardUsageRecordApi({
        storeId: selectedStoreId.value,
        punchCardId: recordFilterForm.templateId || undefined,
        status: recordFilterForm.status,
        keyword: recordKeyword.value.trim() || undefined,
      });

      downloadBase64File(result.fileName, result.fileContentBase64);
      message.success(`导出成功，共 ${result.totalCount} 条`);
    } catch (error) {
      console.error(error);
      message.error('导出失败');
    }
  }

  async function loadScopeOptions() {
    if (!selectedStoreId.value) {
      scopeCategoryOptions.value = [];
      scopeTagOptions.value = [];
      return;
    }

    try {
      const [categories, labels] = await Promise.all([
        getProductCategoryListApi(selectedStoreId.value),
        getProductLabelListApi({
          storeId: selectedStoreId.value,
          status: 'enabled',
        }),
      ]);

      scopeCategoryOptions.value = categories.map((item) => ({
        label: item.name,
        value: item.id,
      }));
      scopeTagOptions.value = labels.map((item) => ({
        label: item.name,
        value: item.id,
      }));
    } catch (error) {
      console.error(error);
      scopeCategoryOptions.value = [];
      scopeTagOptions.value = [];
    }
  }

  watch(selectedStoreId, async () => {
    listPage.value = 1;
    listFilterForm.status = '';
    listKeyword.value = '';

    usagePager.value = {
      ...usagePager.value,
      page: 1,
      pageSize: 10,
    };
    recordFilterForm.templateId = '';
    recordFilterForm.status = '';
    recordKeyword.value = '';

    await Promise.all([
      loadScopeOptions(),
      loadPunchCardList(),
      loadUsageRecords(),
    ]);
  });

  onMounted(async () => {
    await loadStores();
    if (selectedStoreId.value) {
      await Promise.all([
        loadScopeOptions(),
        loadPunchCardList(),
        loadUsageRecords(),
      ]);
    }
  });

  return {
    activeTab,
    applyListFilters,
    applyRecordFilters,
    canManage,
    drawerSubmitText,
    drawerTitle,
    drawerMode,
    exportUsageRecords,
    form,
    handleListPageChange,
    handlePickerCategoryChange,
    handlePickerSearch,
    handleRecordPageChange,
    hasStore,
    isDrawerLoading,
    isDrawerOpen,
    isDrawerSubmitting,
    isListLoading,
    isPickerLoading,
    isPickerOpen,
    isRecordLoading,
    isStoreLoading,
    listFilterForm,
    listKeyword,
    listPage,
    listPageSize,
    listRows,
    listStats,
    listTotalCount,
    openCreateDrawer,
    openEditDrawer,
    openScopeProductPicker,
    pickerCategories,
    pickerCategoryFilterId,
    pickerCategoryOptions,
    pickerKeyword,
    pickerProducts,
    pickerSelectedProductIds,
    recordFilterForm,
    recordKeyword,
    reloadPickerData,
    removeCard,
    resetListFilters,
    resetRecordFilters,
    scopeCategoryOptions,
    scopeTagOptions,
    selectedStoreId,
    setActiveTab,
    setDrawerOpen,
    setFormAllowTransfer,
    setFormCoverImageUrl,
    setFormDailyLimit,
    setFormDescription,
    setFormExpireStrategy,
    setFormName,
    setFormOriginalPrice,
    setFormPerOrderLimit,
    setFormPerUserPurchaseLimit,
    setFormSalePrice,
    setFormScopeType,
    setFormTotalTimes,
    setFormUsageCapAmount,
    setFormUsageMode,
    setFormValidDateRange,
    setFormValidityDays,
    setFormValidityType,
    setListKeyword,
    setListStatusFilter,
    setPickerCategoryFilterId,
    setPickerKeyword,
    setPickerOpen,
    setPickerSelectedProductIds,
    setRecordKeyword,
    setRecordStatusFilter,
    setRecordTemplateFilter,
    setScopeCategoryIds,
    setScopeProductIds,
    setScopeTagIds,
    setSelectedStoreId,
    storeOptions,
    submitDrawer,
    submitPicker,
    templateOptions,
    toggleNotifyChannel,
    togglePickerProduct,
    toggleStatus,
    usagePager,
    usageStats,
  };
}
