import type { OrderHallPageState, OrderHallStatsState } from '../types';

/**
 * 文件职责：订单大厅页面编排器，组合所有子动作模块。
 */
import { onMounted, onUnmounted, reactive, ref, watch } from 'vue';

import { createCardActions } from './order-hall-page/card-actions';
import { createDataActions } from './order-hall-page/data-actions';
import { createNotificationActions } from './order-hall-page/notification-actions';
import { createSignalRActions } from './order-hall-page/signalr-actions';

/** 订单大厅页面 Hook。 */
export function useOrderHallPage() {
  // 1. 页面状态
  const state = reactive<OrderHallPageState>({
    selectedStoreId: '',
    deliveryFilter: 'all',
    isStoreLoading: false,
    isLoading: false,
    isSoundEnabled: true,
    storeOptions: [],
    pendingCards: [],
    makingCards: [],
    deliveringCards: [],
    completedCards: [],
  });

  const stats = ref<OrderHallStatsState>({
    todayTotal: 0,
    pendingCount: 0,
    makingCount: 0,
    deliveringCount: 0,
    completedCount: 0,
  });

  // 2. 拒单弹窗状态
  const isRejectModalOpen = ref(false);
  const rejectingOrderId = ref('');
  const hasSubscribed = ref(false);

  // 3. 创建通知动作
  const notificationActions = createNotificationActions({
    isSoundEnabled: {
      get value() {
        return state.isSoundEnabled;
      },
    },
  });

  // 4. 创建数据动作
  const dataActions = createDataActions({ state, statsRef: stats });

  // 5. 创建 SignalR 动作
  const signalRActions = createSignalRActions({
    state,
    onNewOrder: () => {
      notificationActions.playNewOrderSound();
      notificationActions.showDesktopNotification(
        '新订单',
        '有新订单到达，请及时处理',
      );
    },
    onUrge: () => {
      notificationActions.playUrgeSound();
    },
    catchUpSince: dataActions.catchUpSince,
    loadFullBoard: dataActions.loadFullBoard,
    loadStats: dataActions.loadStats,
  });

  // 6. 刷新回调
  async function refresh(): Promise<void> {
    await Promise.all([dataActions.loadFullBoard(), dataActions.loadStats()]);
  }

  // 7. 创建卡片动作
  const cardActions = createCardActions({
    onRefresh: refresh,
    onAccepted: () => {
      // 接单后如果待接单列为空则停止声音
      if (state.pendingCards.length <= 1) {
        notificationActions.stopNewOrderSound();
      }
    },
  });

  // 8. 拒单流程
  function openRejectModal(orderId: string): void {
    rejectingOrderId.value = orderId;
    isRejectModalOpen.value = true;
  }

  async function confirmReject(reason: string): Promise<void> {
    await cardActions.handleReject(rejectingOrderId.value, reason);
    isRejectModalOpen.value = false;
    rejectingOrderId.value = '';
  }

  function cancelReject(): void {
    isRejectModalOpen.value = false;
    rejectingOrderId.value = '';
  }

  // 9. 监听门店切换
  watch(
    () => state.selectedStoreId,
    async (newStoreId) => {
      if (!newStoreId) {
        return;
      }
      await refresh();

      if (!hasSubscribed.value) {
        await signalRActions.connectAndSubscribe();
        hasSubscribed.value = true;
        return;
      }

      await signalRActions.switchStore(newStoreId);
    },
  );

  // 10. 监听提示音开关（关闭时立即停掉循环音）
  watch(
    () => state.isSoundEnabled,
    (enabled) => {
      if (!enabled) {
        notificationActions.stopNewOrderSound();
      }
    },
  );

  // 11. 生命周期
  onMounted(async () => {
    notificationActions.requestNotificationPermission();
    await dataActions.loadStores();
  });

  onUnmounted(() => {
    signalRActions.disconnect();
    notificationActions.stopNewOrderSound();
  });

  return {
    state,
    stats,
    isRejectModalOpen,
    isConnected: signalRActions.isConnected,
    // 数据
    loadFullBoard: dataActions.loadFullBoard,
    loadStores: dataActions.loadStores,
    loadStats: dataActions.loadStats,
    // 卡片操作
    handleAccept: cardActions.handleAccept,
    handleCompletePreparation: cardActions.handleCompletePreparation,
    handleConfirmDelivery: cardActions.handleConfirmDelivery,
    openRejectModal,
    confirmReject,
    cancelReject,
    // SignalR
    connectAndSubscribe: signalRActions.connectAndSubscribe,
  };
}
