"use client";

import { useCallback, useEffect, useRef } from "react";

import { useNetworkConnectionStore } from "@/stores/network-connection-store";
import {
  refreshWalletNow,
  startLimitedWalletPolling,
  startPersistentWalletPolling,
  stopWalletPolling,
} from "@/lib/wallet-polling-utils";

export type UseWalletPollingReturn = {
  /** 开始钱包轮询（持续或限时） */
  startWalletPolling: (options?: { limitedDuration?: boolean }) => void;
  /** 停止钱包轮询 */
  stopWalletPolling: () => void;
  /** 立即刷新钱包余额 */
  refreshWallet: () => Promise<void>;
  /** 是否正在轮询中 */
  isPolling: boolean;
};

/**
 * 钱包余额轮询 Hook
 * 用于：
 * 1. WebSocket 降级模式下的余额同步
 * 2. 下注后的限时轮询（2分钟）
 * 3. 开奖结果后的限时轮询（2分钟）
 */
export function useWalletPolling(): UseWalletPollingReturn {
  // 使用 selector 避免整 store 订阅导致无谓重渲染
  const walletPollingIntervalId = useNetworkConnectionStore(
    (s) => s.walletPollingIntervalId,
  );

  const intervalIdRef = useRef<number | null>(walletPollingIntervalId);

  // 同步 ref 和 store 状态
  useEffect(() => {
    intervalIdRef.current = walletPollingIntervalId;
  }, [walletPollingIntervalId]);

  // 开始钱包轮询（委托给共享工具函数）
  const startWalletPolling = useCallback(
    (options?: { limitedDuration?: boolean }) => {
      const { limitedDuration = false } = options ?? {};

      if (limitedDuration) {
        startLimitedWalletPolling();
      } else {
        startPersistentWalletPolling();
      }
    },
    [],
  );

  // 停止钱包轮询
  const handleStop = useCallback(() => {
    if (intervalIdRef.current) {
      window.clearInterval(intervalIdRef.current);
      intervalIdRef.current = null;
    }
    stopWalletPolling();
  }, []);

  // 组件卸载时清理
  useEffect(() => {
    return () => {
      if (intervalIdRef.current) {
        window.clearInterval(intervalIdRef.current);
      }
    };
  }, []);

  return {
    startWalletPolling,
    stopWalletPolling: handleStop,
    refreshWallet: refreshWalletNow,
    isPolling: walletPollingIntervalId !== null,
  };
}

/**
 * 全局钱包轮询触发器
 * 用于在非 React 上下文（如事件监听）中触发钱包轮询
 */
export function triggerWalletPollingAfterBet(): void {
  const store = useNetworkConnectionStore.getState();

  if (store.mode === "polling" || store.mode === "offline") {
    startLimitedWalletPolling();
    return;
  }

  window.dispatchEvent(new Event("lottery-wallet-refresh"));
}
