import type {
  CostDeleteModalState,
  CostDetailDrawerState,
  FinanceCostAnalysisState,
  FinanceCostEntryState,
  FinanceCostFilterState,
  FinanceCostTabKey,
  OptionItem,
} from '../types';

/**
 * 文件职责：成本管理页面状态与动作编排。
 */
import type { FinanceCostCategoryCode } from '#/api/finance/cost';
import type { StoreListItemDto } from '#/api/store';

import { computed, onActivated, onMounted, reactive, ref, watch } from 'vue';

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

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

import {
  COST_DIMENSION_OPTIONS,
  COST_TAB_OPTIONS,
  DEFAULT_ANALYSIS_STATE,
  DEFAULT_ENTRY_STATE,
  DEFAULT_FILTER_STATE,
  FINANCE_COST_MANAGE_PERMISSION,
  FINANCE_COST_VIEW_PERMISSION,
} from './cost-page/constants';
import { createDataActions } from './cost-page/data-actions';
import { createDrawerActions } from './cost-page/drawer-actions';
import { createEntryActions } from './cost-page/entry-actions';
import { createFilterActions } from './cost-page/filter-actions';
import { formatMonthTitle, getCurrentMonthString } from './cost-page/helpers';

/** 创建成本管理页面组合状态。 */
export function useFinanceCostPage() {
  const accessStore = useAccessStore();

  const stores = ref<StoreListItemDto[]>([]);
  const activeTab = ref<FinanceCostTabKey>('entry');
  const filters = reactive<FinanceCostFilterState>({
    ...DEFAULT_FILTER_STATE,
    month: getCurrentMonthString(),
  });

  const entry = reactive<FinanceCostEntryState>({
    ...DEFAULT_ENTRY_STATE,
  });
  const analysis = reactive<FinanceCostAnalysisState>({
    ...DEFAULT_ANALYSIS_STATE,
  });

  const isStoreLoading = ref(false);
  const isEntryLoading = ref(false);
  const isAnalysisLoading = ref(false);
  const isSaving = ref(false);

  const drawerState = reactive<CostDetailDrawerState>({
    open: false,
    mode: 'create',
    category: 'food',
  });
  const deleteModalState = reactive<CostDeleteModalState>({
    open: false,
    category: 'food',
  });

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

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

  const selectedStoreName = computed(
    () =>
      storeOptions.value.find((item) => item.value === filters.storeId)
        ?.label ?? '--',
  );

  const monthTitle = computed(() => formatMonthTitle(filters.month));
  const showStoreSelect = computed(() => filters.dimension === 'store');
  const hasStore = computed(() => stores.value.length > 0);
  const canQueryCurrentScope = computed(
    () => filters.dimension === 'tenant' || Boolean(filters.storeId),
  );
  const drawerCategoryText = computed(() => {
    const matched = entry.categories.find(
      (item) => item.category === drawerState.category,
    );
    return matched?.categoryText || '明细';
  });
  const tabOptions = computed(() => COST_TAB_OPTIONS);
  const dimensionOptions = computed(() => COST_DIMENSION_OPTIONS);

  const dataActions = createDataActions({
    stores,
    filters,
    entry,
    analysis,
    isStoreLoading,
    isEntryLoading,
    isAnalysisLoading,
    isSaving,
  });
  const entryActions = createEntryActions({ entry });
  const filterActions = createFilterActions({ activeTab, filters });
  const drawerActions = createDrawerActions({
    drawerState,
    deleteModalState,
    upsertDetailItem: entryActions.upsertDetailItem,
    removeDetailItem: entryActions.removeDetailItem,
  });

  async function loadByCurrentTab() {
    if (!canView.value) return;
    if (!canQueryCurrentScope.value) {
      if (activeTab.value === 'entry') {
        dataActions.clearEntry();
      } else {
        dataActions.clearAnalysis();
      }
      return;
    }

    if (activeTab.value === 'entry') {
      await dataActions.loadEntryData();
      return;
    }

    await dataActions.loadAnalysisData();
  }

  async function loadAllPanels() {
    if (!canView.value || !canQueryCurrentScope.value) return;
    await Promise.all([
      dataActions.loadEntryData(),
      dataActions.loadAnalysisData(),
    ]);
  }

  function ensureStoreSelection() {
    if (filters.dimension !== 'store') return;
    if (filters.storeId) return;
    if (stores.value.length === 0) return;
    filters.storeId = stores.value[0]?.id ?? '';
  }

  function clearByPermission() {
    stores.value = [];
    filters.storeId = '';
    dataActions.clearAllData();
    drawerActions.closeDrawer();
    drawerActions.closeDeleteModal();
  }

  async function initPageData() {
    if (!canView.value) {
      clearByPermission();
      return;
    }

    await dataActions.loadStores();
    ensureStoreSelection();
    await loadByCurrentTab();
  }

  async function saveEntry() {
    if (!canManage.value) {
      message.warning('当前账号没有维护权限');
      return;
    }

    await dataActions.saveEntryData();
    await dataActions.loadAnalysisData();
  }

  function openAddDetail(category: FinanceCostCategoryCode) {
    if (!canManage.value) {
      message.warning('当前账号没有维护权限');
      return;
    }
    drawerActions.openCreateDrawer(category);
  }

  function openEditDetail(category: FinanceCostCategoryCode, itemId: string) {
    if (!canManage.value) {
      message.warning('当前账号没有维护权限');
      return;
    }

    const targetCategory = entry.categories.find(
      (current) => current.category === category,
    );
    const targetItem = targetCategory?.items.find(
      (current) => current.itemId === itemId,
    );
    if (!targetItem) return;
    drawerActions.openEditDrawer(category, targetItem);
  }

  function openDeleteDetail(category: FinanceCostCategoryCode, itemId: string) {
    if (!canManage.value) {
      message.warning('当前账号没有维护权限');
      return;
    }

    const targetCategory = entry.categories.find(
      (current) => current.category === category,
    );
    const targetItem = targetCategory?.items.find(
      (current) => current.itemId === itemId,
    );
    if (!targetItem) return;
    drawerActions.openDeleteModal(category, targetItem);
  }

  watch(
    () => activeTab.value,
    async () => {
      await loadByCurrentTab();
    },
  );

  watch(
    () => [filters.dimension, filters.storeId, filters.month],
    async () => {
      if (filters.dimension === 'store') {
        ensureStoreSelection();
      }
      await loadByCurrentTab();
    },
  );

  watch(
    () => canView.value,
    async (value, oldValue) => {
      if (value === oldValue) return;
      if (!value) {
        clearByPermission();
        return;
      }
      await initPageData();
    },
  );

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

  onActivated(() => {
    if (!canView.value) return;
    if (stores.value.length === 0) {
      void initPageData();
    }
  });

  return {
    activeTab,
    analysis,
    canManage,
    canQueryCurrentScope,
    canView,
    deleteModalState,
    dimensionOptions,
    drawerCategoryText,
    drawerState,
    entry,
    filters,
    hasStore,
    isAnalysisLoading,
    isEntryLoading,
    isSaving,
    isStoreLoading,
    loadAllPanels,
    monthTitle,
    openAddDetail,
    openDeleteDetail,
    openEditDetail,
    saveEntry,
    selectedStoreName,
    setActiveTab: filterActions.setActiveTab,
    setCategoryTotal: entryActions.setCategoryTotal,
    setDimension: filterActions.setDimension,
    setMonth: filterActions.setMonth,
    setNextMonth: filterActions.setNextMonth,
    setPreviousMonth: filterActions.setPreviousMonth,
    setStoreId: filterActions.setStoreId,
    showStoreSelect,
    storeOptions,
    submitDetailFromDrawer: drawerActions.submitDrawer,
    tabOptions,
    toggleCategoryExpanded: entryActions.toggleCategoryExpanded,
    closeDetailDrawer: drawerActions.closeDrawer,
    closeDeleteModal: drawerActions.closeDeleteModal,
    confirmDeleteDetail: drawerActions.confirmDelete,
  };
}
