/**
 * 营业时间页面主编排：
 * 1. 维护页面级响应式状态
 * 2. 组装各子域 action（加载、每周时段、日期、复制）
 * 3. 对外暴露视图层可直接消费的状态与方法
 */
import type {
  AddSlotFormState,
  DayEditFormState,
  HolidayFormState,
} from '../types';

import type { StoreListItemDto } from '#/api/store';
import type { DayHoursDto, HolidayDto } from '#/api/store-hours';

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

import { HolidayType, SlotType } from '#/api/store-hours';

import { createAddSlotActions } from './store-hours-page/add-slot-actions';
import {
  DAY_NAMES,
  DEFAULT_DAY_NAME,
  SLOT_TYPE_OPTIONS,
} from './store-hours-page/constants';
import { createCopyActions } from './store-hours-page/copy-actions';
import { createDataActions } from './store-hours-page/data-actions';
import { createDayEditActions } from './store-hours-page/day-edit-actions';
import {
  cloneWeeklyHours,
  createSlotId,
  formatHolidayDate,
  formatHolidayTime,
  getHolidayTagStyle,
  getHolidayTypeText,
  getLegendDotColor,
  getSlotStyle,
  getSlotTypeLabel,
  getSlotTypePillClass,
  getTodayDate,
  normalizeHolidays,
  normalizeWeeklyHours,
  parseTimeToMinutes,
  sortSlots,
  toDateOnly,
  toTimeHHmm,
  validateDaySlots,
  validateSlot,
} from './store-hours-page/helpers';
import { createHolidayActions } from './store-hours-page/holiday-actions';
import { createWeeklyActions } from './store-hours-page/weekly-actions';

export function useStoreHoursPage() {
  // 1. 页面级 loading / submitting 状态。
  const isStoreLoading = ref(false);
  const isHoursLoading = ref(false);
  const isWeeklySubmitting = ref(false);
  const isHolidaySubmitting = ref(false);
  const isCopySubmitting = ref(false);
  const deletingHolidayId = ref('');

  // 2. 页面核心业务数据。
  const stores = ref<StoreListItemDto[]>([]);
  const selectedStoreId = ref('');
  const weeklyHours = ref<DayHoursDto[]>([]);
  const holidays = ref<HolidayDto[]>([]);

  // 3. 抽屉/弹窗可见性。
  const isAddDrawerOpen = ref(false);
  const isDayDrawerOpen = ref(false);
  const isHolidayDrawerOpen = ref(false);
  const isCopyModalOpen = ref(false);

  // 4. 各子模块表单状态。
  const addSlotForm = reactive<AddSlotFormState>({
    type: SlotType.Business,
    selectedDays: [0, 1, 2, 3, 4],
    startTime: '09:00',
    endTime: '22:00',
    capacity: 50,
    remark: '',
  });

  const dayEditForm = reactive<DayEditFormState>({
    dayOfWeek: 0,
    isOpen: true,
    slots: [],
  });

  const holidayDrawerMode = ref<'create' | 'edit'>('create');
  const holidayForm = reactive<HolidayFormState>({
    id: '',
    type: HolidayType.Closed,
    dateMode: 'single',
    singleDate: '',
    rangeStart: '',
    rangeEnd: '',
    startTime: '09:00',
    endTime: '22:00',
    reason: '',
    remark: '',
  });

  const copyTargetStoreIds = ref<string[]>([]);

  // 5. 页面衍生视图数据。
  const storeOptions = computed(() =>
    stores.value.map((store) => ({ label: store.name, value: store.id })),
  );

  const copyCandidates = computed(() =>
    stores.value.filter((store) => store.id !== selectedStoreId.value),
  );

  const selectedStoreName = computed(
    () =>
      stores.value.find((store) => store.id === selectedStoreId.value)?.name ??
      '',
  );

  const weekRows = computed(() =>
    normalizeWeeklyHours(weeklyHours.value).map((day, index) => {
      const dayMeta = DAY_NAMES[index] ?? DEFAULT_DAY_NAME;
      return {
        ...day,
        label: dayMeta.label,
        labelEn: dayMeta.labelEn,
        slots: sortSlots(day.slots),
      };
    }),
  );

  const holidayRows = computed(() => normalizeHolidays(holidays.value));

  const currentDayMeta = computed(
    () => DAY_NAMES[dayEditForm.dayOfWeek] ?? DEFAULT_DAY_NAME,
  );

  const holidayDrawerTitle = computed(() =>
    holidayDrawerMode.value === 'edit' ? '编辑日期' : '添加日期',
  );

  const holidaySubmitText = computed(() =>
    holidayDrawerMode.value === 'edit' ? '保存修改' : '确认添加',
  );

  const isCopyAllChecked = computed(
    () =>
      copyCandidates.value.length > 0 &&
      copyTargetStoreIds.value.length === copyCandidates.value.length,
  );

  const isCopyIndeterminate = computed(
    () =>
      copyTargetStoreIds.value.length > 0 &&
      copyTargetStoreIds.value.length < copyCandidates.value.length,
  );

  // 6. 数据加载域 action。
  const { loadStoreHours, loadStores } = createDataActions({
    holidays,
    isHoursLoading,
    isStoreLoading,
    normalizeHolidays,
    normalizeWeeklyHours,
    selectedStoreId,
    stores,
    weeklyHours,
  });

  const { persistWeeklyHours } = createWeeklyActions({
    isWeeklySubmitting,
    loadStoreHours,
    normalizeWeeklyHours,
    selectedStoreId,
  });

  // 7. 添加时段域 action。
  const {
    handleAddSlotSubmit,
    isAddDaySelected,
    openAddSlotDrawer,
    quickSelectAddDays,
    setAddSlotCapacity,
    setAddSlotEndTime,
    setAddSlotRemark,
    setAddSlotStartTime,
    setAddSlotType,
    toggleAddDay,
  } = createAddSlotActions({
    addSlotForm,
    cloneWeeklyHours,
    createSlotId,
    defaultDayName: DEFAULT_DAY_NAME,
    dayNames: DAY_NAMES,
    isAddDrawerOpen,
    persistWeeklyHours,
    selectedStoreId,
    sortSlots,
    validateDaySlots,
    validateSlot,
    weeklyHours,
  });

  // 8. 日编辑域 action。
  const {
    addDaySlotRow,
    handleSaveDay,
    openDayDrawer,
    removeDaySlot,
    setDayEditOpen,
    setDaySlotCapacity,
    setDaySlotEndTime,
    setDaySlotStartTime,
    setDaySlotType,
  } = createDayEditActions({
    cloneWeeklyHours,
    createSlotId,
    currentDayMeta,
    dayEditForm,
    isDayDrawerOpen,
    normalizeWeeklyHours,
    persistWeeklyHours,
    selectedStoreId,
    sortSlots,
    validateDaySlots,
    weeklyHours,
  });

  // 9. 节假日域 action。
  const {
    handleDeleteHoliday,
    handleHolidaySubmit,
    openHolidayDrawer,
    setHolidayDateMode,
    setHolidayEndTime,
    setHolidayRangeEnd,
    setHolidayRangeStart,
    setHolidayReason,
    setHolidayRemark,
    setHolidaySingleDate,
    setHolidayStartTime,
    setHolidayType,
  } = createHolidayActions({
    deletingHolidayId,
    getTodayDate,
    holidayDrawerMode,
    holidayForm,
    isHolidayDrawerOpen,
    isHolidaySubmitting,
    loadStoreHours,
    parseTimeToMinutes,
    selectedStoreId,
    toDateOnly,
    toTimeHHmm,
  });

  // 10. 复制域 action。
  const {
    handleCopyCheckAll,
    handleCopyStoreChange,
    handleCopySubmit,
    openCopyModal,
    toggleCopyStore,
  } = createCopyActions({
    copyCandidates,
    copyTargetStoreIds,
    isCopyModalOpen,
    isCopySubmitting,
    selectedStoreId,
  });

  // 11. 门店切换后自动刷新对应营业时间。
  watch(selectedStoreId, async (storeId) => {
    if (!storeId) {
      weeklyHours.value = normalizeWeeklyHours([]);
      holidays.value = [];
      return;
    }
    await loadStoreHours(storeId);
  });

  // 12. 页面首屏初始化。
  onMounted(loadStores);
  // 13. 路由回到当前页时刷新门店列表，避免使用旧缓存。
  onActivated(loadStores);

  return {
    DAY_NAMES,
    HolidayType,
    SLOT_TYPE_OPTIONS,
    SlotType,

    addDaySlotRow,
    addSlotForm,
    copyCandidates,
    copyTargetStoreIds,
    currentDayMeta,
    dayEditForm,
    deletingHolidayId,
    formatHolidayDate,
    formatHolidayTime,
    getHolidayTagStyle,
    getHolidayTypeText,
    getLegendDotColor,
    getSlotStyle,
    getSlotTypeLabel,
    getSlotTypePillClass,
    handleAddSlotSubmit,
    handleCopyCheckAll,
    handleCopyStoreChange,
    handleCopySubmit,
    handleDeleteHoliday,
    handleHolidaySubmit,
    handleSaveDay,
    holidayDrawerTitle,
    holidayForm,
    holidayRows,
    holidaySubmitText,
    isAddDaySelected,
    isAddDrawerOpen,
    isCopyAllChecked,
    isCopyIndeterminate,
    isCopyModalOpen,
    isCopySubmitting,
    isDayDrawerOpen,
    isHolidayDrawerOpen,
    isHolidaySubmitting,
    isHoursLoading,
    isStoreLoading,
    isWeeklySubmitting,
    openAddSlotDrawer,
    openCopyModal,
    openDayDrawer,
    openHolidayDrawer,
    quickSelectAddDays,
    removeDaySlot,
    selectedStoreId,
    selectedStoreName,
    setAddSlotCapacity,
    setAddSlotEndTime,
    setAddSlotRemark,
    setAddSlotStartTime,
    setAddSlotType,
    setDayEditOpen,
    setDaySlotCapacity,
    setDaySlotEndTime,
    setDaySlotStartTime,
    setDaySlotType,
    setHolidayDateMode,
    setHolidayEndTime,
    setHolidayRangeEnd,
    setHolidayRangeStart,
    setHolidayReason,
    setHolidayRemark,
    setHolidaySingleDate,
    setHolidayStartTime,
    setHolidayType,
    storeOptions,
    toggleAddDay,
    toggleCopyStore,
    weekRows,
  };
}
