import type {
  ProductSpecCardViewModel,
  SpecEditorForm,
  SpecsTypeFilter,
} from '../types';

import type { StoreListItemDto } from '#/api/store';

/**
 * 文件职责：规格做法页面状态与行为编排。
 * 1. 管理门店、模板列表、筛选与统计状态。
 * 2. 封装模板新增/编辑/删除/复制流程。
 */
import {
  computed,
  onBeforeUnmount,
  onMounted,
  reactive,
  ref,
  watch,
} from 'vue';

import { createDefaultOption } from './specs-page/constants';
import { createDataActions } from './specs-page/data-actions';
import { createDrawerActions } from './specs-page/drawer-actions';
import { createTemplateActions } from './specs-page/template-actions';

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

  const rows = ref<ProductSpecCardViewModel[]>([]);
  const isLoading = ref(false);
  const keyword = ref('');
  const typeFilter = ref<SpecsTypeFilter>('all');

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

  const form = reactive<SpecEditorForm>({
    id: '',
    name: '',
    type: 'spec',
    selectionType: 'single',
    isRequired: true,
    sort: 1,
    status: 'enabled',
    productIds: [],
    values: [createDefaultOption()],
  });

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

  const filteredRows = computed(() => {
    if (typeFilter.value === 'all') {
      return rows.value;
    }
    return rows.value.filter((item) => item.type === typeFilter.value);
  });

  const specCount = computed(
    () => rows.value.filter((item) => item.type === 'spec').length,
  );

  const methodCount = computed(
    () => rows.value.filter((item) => item.type === 'method').length,
  );

  const totalProducts = computed(() =>
    rows.value.reduce((sum, item) => sum + item.productCount, 0),
  );

  const drawerTitle = computed(() =>
    drawerMode.value === 'create' ? '添加模板' : '编辑模板',
  );

  const drawerSubmitText = computed(() =>
    drawerMode.value === 'create' ? '确认添加' : '保存修改',
  );

  const { loadSpecs, loadStores } = createDataActions({
    stores,
    selectedStoreId,
    isStoreLoading,
    rows,
    isLoading,
    keyword,
  });

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

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

  function setTypeFilter(value: SpecsTypeFilter) {
    typeFilter.value = value;
  }

  const {
    addOption,
    openCreateDrawer,
    openEditDrawer,
    removeOption,
    setDrawerOpen,
    setFormIsRequired,
    setFormName,
    setFormSelectionType,
    setFormType,
    setOptionExtraPrice,
    setOptionName,
    submitDrawer,
  } = createDrawerActions({
    drawerMode,
    form,
    isDrawerOpen,
    isDrawerSubmitting,
    loadSpecs,
    rows,
    selectedStoreId,
  });

  const { copyTemplate, removeTemplate } = createTemplateActions({
    selectedStoreId,
    loadSpecs,
  });

  let keywordSearchTimer: null | ReturnType<typeof setTimeout> = null;

  watch(selectedStoreId, () => {
    keyword.value = '';
    typeFilter.value = 'all';
    void loadSpecs();
  });

  watch(keyword, () => {
    if (!selectedStoreId.value) return;
    if (keywordSearchTimer) {
      clearTimeout(keywordSearchTimer);
      keywordSearchTimer = null;
    }
    keywordSearchTimer = setTimeout(() => {
      void loadSpecs();
      keywordSearchTimer = null;
    }, 220);
  });

  onBeforeUnmount(() => {
    if (keywordSearchTimer) {
      clearTimeout(keywordSearchTimer);
      keywordSearchTimer = null;
    }
  });

  onMounted(loadStores);

  return {
    drawerSubmitText,
    drawerTitle,
    filteredRows,
    form,
    isDrawerOpen,
    isDrawerSubmitting,
    isLoading,
    isStoreLoading,
    keyword,
    methodCount,
    openCreateDrawer,
    openEditDrawer,
    removeOption,
    removeTemplate,
    copyTemplate,
    loadSpecs,
    selectedStoreId,
    setDrawerOpen,
    setFormIsRequired,
    setFormName,
    setFormSelectionType,
    setFormType,
    setKeyword,
    setOptionExtraPrice,
    setOptionName,
    setSelectedStoreId,
    setTypeFilter,
    specCount,
    storeOptions,
    submitDrawer,
    totalProducts,
    typeFilter,
    addOption,
  };
}
