import type { ProductPickerItemDto, ProductScheduleDto } from '#/api/product';
import type { StoreListItemDto } from '#/api/store';
import type {
  ScheduleEditorForm,
  ScheduleProductChip,
  ScheduleProductLookup,
} from '#/views/product/schedule/types';

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

import {
  createDefaultScheduleForm,
  resolveScheduleColor,
} from './schedule-page/constants';
import { createDataActions } from './schedule-page/data-actions';
import { createDrawerActions } from './schedule-page/drawer-actions';
import { createRuleActions } from './schedule-page/rule-actions';
import {
  buildTimelineRow,
  getTodayWeekDay,
} from './schedule-page/timeline-utils';

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

  const rows = ref<ProductScheduleDto[]>([]);
  const isLoading = ref(false);
  const keyword = ref('');

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

  const form = reactive<ScheduleEditorForm>(createDefaultScheduleForm());

  const isPickerOpen = ref(false);
  const isPickerLoading = ref(false);
  const pickerKeyword = ref('');
  const pickerProducts = ref<ProductPickerItemDto[]>([]);
  const pickerSelectedIds = ref<string[]>([]);

  const productLookup = ref<ScheduleProductLookup>({});

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

  const filteredRows = computed(() => {
    const normalized = keyword.value.trim().toLowerCase();
    if (!normalized) return rows.value;
    return rows.value.filter((item) =>
      item.name.toLowerCase().includes(normalized),
    );
  });

  const ruleCount = computed(() => rows.value.length);

  const enabledCount = computed(
    () => rows.value.filter((item) => item.status === 'enabled').length,
  );

  const coveredProductCount = computed(() => {
    const idSet = new Set<string>();
    for (const item of rows.value) {
      for (const productId of item.productIds) {
        idSet.add(productId);
      }
    }

    return idSet.size;
  });

  const drawerTitle = computed(() =>
    drawerMode.value === 'create' ? '添加时段规则' : '编辑时段规则',
  );

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

  const selectedProducts = computed<ScheduleProductChip[]>(() =>
    form.productIds.map((id) => ({
      id,
      name: resolveProductName(id),
    })),
  );

  const timelineRows = computed(() => {
    const today = getTodayWeekDay();
    return filteredRows.value
      .filter((item) => item.weekDays.includes(today))
      .map((item) => buildTimelineRow(item, getRuleColor(item.id)));
  });

  function getRuleColor(scheduleId: string | undefined) {
    return resolveScheduleColor(scheduleId || '');
  }

  function resolveProductName(productId: string) {
    const product = productLookup.value[productId];
    if (product) return product.name;

    const suffix = productId.length > 4 ? productId.slice(-4) : productId;
    return `商品${suffix}`;
  }

  function getScheduleProductNames(item: ProductScheduleDto) {
    return item.productIds.map((id) => resolveProductName(id));
  }

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

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

  const {
    loadPickerProducts,
    loadSchedules,
    loadStores,
    preloadProductLookup,
  } = createDataActions({
    stores,
    selectedStoreId,
    isStoreLoading,
    rows,
    isLoading,
    isPickerLoading,
    pickerKeyword,
    pickerProducts,
    productLookup,
  });

  const {
    openCreateDrawer,
    openEditDrawer,
    openProductPicker,
    removeFormProduct,
    selectAllDays,
    selectWeekdays,
    selectWeekend,
    setDrawerOpen,
    setFormEndTime,
    setFormName,
    setFormStartTime,
    setPickerKeyword,
    setPickerOpen,
    submitDrawer,
    submitPicker,
    toggleFormStatus,
    togglePickerProduct,
    toggleWeekDay,
  } = createDrawerActions({
    drawerMode,
    editingScheduleId,
    form,
    isDrawerOpen,
    isDrawerSubmitting,
    isPickerOpen,
    pickerKeyword,
    pickerSelectedIds,
    rows,
    selectedStoreId,
    loadSchedules,
    loadPickerProducts,
  });

  const { removeRule, toggleRuleStatus } = createRuleActions({
    selectedStoreId,
    loadSchedules,
  });

  watch(selectedStoreId, () => {
    keyword.value = '';
    void Promise.all([loadSchedules(), preloadProductLookup()]);
  });

  onMounted(loadStores);

  return {
    coveredProductCount,
    drawerSubmitText,
    drawerTitle,
    enabledCount,
    filteredRows,
    form,
    getRuleColor,
    getScheduleProductNames,
    isDrawerOpen,
    isDrawerSubmitting,
    isLoading,
    isPickerLoading,
    isPickerOpen,
    isStoreLoading,
    keyword,
    loadPickerProducts,
    openCreateDrawer,
    openEditDrawer,
    openProductPicker,
    pickerKeyword,
    pickerProducts,
    pickerSelectedIds,
    removeFormProduct,
    removeRule,
    ruleCount,
    selectAllDays,
    selectedProducts,
    selectedStoreId,
    selectWeekdays,
    selectWeekend,
    setDrawerOpen,
    setFormEndTime,
    setFormName,
    setFormStartTime,
    setKeyword,
    setPickerKeyword,
    setPickerOpen,
    setSelectedStoreId,
    storeOptions,
    submitDrawer,
    submitPicker,
    timelineRows,
    toggleFormStatus,
    togglePickerProduct,
    toggleRuleStatus,
    toggleWeekDay,
  };
}
