/**
 * 连接状态 Hook
 * 
 * 提供连接状态的 React Hook 接口
 * 订阅 ConnectionStateManager 状态变化
 */

import { useState, useEffect, useCallback, useMemo } from 'react';
import {
  ConnectionState,
  ConnectionStateInfo,
  connectionStateManager,
} from '../infrastructure/sync';

/**
 * useConnectionState Hook 返回值接口
 */
export interface UseConnectionStateResult {
  /** 当前连接状态 */
  state: ConnectionState;
  /** 完整的状态信息 */
  stateInfo: ConnectionStateInfo;
  /** 是否已连接 */
  isConnected: boolean;
  /** 是否正在连接（包括 CONNECTING 和 RECONNECTING） */
  isConnecting: boolean;
  /** 是否正在重连 */
  isReconnecting: boolean;
  /** 是否已断开 */
  isDisconnected: boolean;
  /** 是否处于错误状态 */
  hasError: boolean;
  /** 当前错误信息 */
  error: Error | null;
  /** 当前重连次数 */
  reconnectAttempts: number;
  /** 最大重连次数 */
  maxReconnectAttempts: number;
  /** 最后连接时间 */
  lastConnectedAt: number | null;
  /** 状态描述文本 */
  description: string;
  /** 手动触发重连 */
  triggerReconnect: () => void;
  /** 重置重连次数 */
  resetReconnectAttempts: () => void;
}

/**
 * 连接状态 Hook
 * 
 * 订阅 ConnectionStateManager 的状态变化，
 * 提供便捷的状态属性和方法
 * 
 * @example
 * ```tsx
 * function ConnectionStatus() {
 *   const { state, isConnected, isConnecting, description } = useConnectionState();
 *   
 *   return (
 *     <View>
 *       <Text>{description}</Text>
 *       {isConnecting && <ActivityIndicator />}
 *     </View>
 *   );
 * }
 * ```
 */
export function useConnectionState(): UseConnectionStateResult {
  // 状态
  const [stateInfo, setStateInfo] = useState<ConnectionStateInfo>(() => 
    connectionStateManager.getState()
  );

  // 订阅状态变化
  useEffect(() => {
    const unsubscribe = connectionStateManager.subscribe((newState) => {
      setStateInfo(newState);
    });

    return unsubscribe;
  }, []);

  // 计算派生状态
  const isConnected = useMemo(() => 
    stateInfo.state === ConnectionState.CONNECTED,
    [stateInfo.state]
  );

  const isConnecting = useMemo(() => 
    stateInfo.state === ConnectionState.CONNECTING || 
    stateInfo.state === ConnectionState.RECONNECTING,
    [stateInfo.state]
  );

  const isReconnecting = useMemo(() => 
    stateInfo.state === ConnectionState.RECONNECTING,
    [stateInfo.state]
  );

  const isDisconnected = useMemo(() => 
    stateInfo.state === ConnectionState.DISCONNECTED ||
    stateInfo.state === ConnectionState.IDLE,
    [stateInfo.state]
  );

  const hasError = useMemo(() => 
    stateInfo.state === ConnectionState.ERROR,
    [stateInfo.state]
  );

  // 手动触发重连
  const triggerReconnect = useCallback(() => {
    // 只有在断开或错误状态才能触发重连
    if (
      stateInfo.state === ConnectionState.DISCONNECTED ||
      stateInfo.state === ConnectionState.ERROR ||
      stateInfo.state === ConnectionState.IDLE
    ) {
      connectionStateManager.setState(ConnectionState.RECONNECTING);
    }
  }, [stateInfo.state]);

  // 重置重连次数
  const resetReconnectAttempts = useCallback(() => {
    connectionStateManager.resetReconnectAttempts();
  }, []);

  return {
    state: stateInfo.state,
    stateInfo,
    isConnected,
    isConnecting,
    isReconnecting,
    isDisconnected,
    hasError,
    error: stateInfo.error || null,
    reconnectAttempts: stateInfo.reconnectAttempts || 0,
    maxReconnectAttempts: connectionStateManager.getMaxReconnectAttempts(),
    lastConnectedAt: stateInfo.lastConnectedAt || null,
    description: stateInfo.description,
    triggerReconnect,
    resetReconnectAttempts,
  };
}

export default useConnectionState;
