import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_webrtc/flutter_webrtc.dart';
import 'package:vsdk/app_player.dart';

import '../../../../enums/video_stream_mode_enum.dart';
import '../../../../services/webrtc_service.dart';
import 'video_fullscreen_page.dart';
import 'video_stream_switch.dart';

/// 通用实时视频播放组件（兼容 WebRTC + P2P 双模式）
///
/// 职责：
/// - WebRTC 模式：通过 [RTCVideoView] 渲染远程摄像头实时画面
/// - P2P 模式：通过 [AppPlayerView] 渲染 Texture 视频画面
/// - 依据当前模式的连接状态显示对应的状态指示器
/// - 右下角提供模式切换按钮（P2P/RTC）和全屏按钮
///
/// 涉及页面：监控页 - 监控画面
class VideoPlayerWidget extends StatelessWidget {
  /// 当前视频传输模式
  final VideoStreamMode streamMode;

  /// 是否正在切换模式
  final bool isSwitchingMode;

  /// WebRTC 视频渲染器（WebRTC 模式时使用）
  final RTCVideoRenderer? webrtcRenderer;

  /// WebRTC 连接状态
  final WebrtcConnectionState webrtcConnectionState;

  /// P2P 视频播放控制器（P2P 模式时使用）
  final AppPlayerController? p2pController;

  /// P2P 模式是否已连接
  final bool isP2pConnected;

  /// 连接失败时点击重试回调
  final VoidCallback? onRetry;

  /// 模式切换回调
  final VoidCallback? onToggleMode;

  const VideoPlayerWidget({
    super.key,
    required this.streamMode,
    this.isSwitchingMode = false,
    this.webrtcRenderer,
    required this.webrtcConnectionState,
    this.p2pController,
    this.isP2pConnected = false,
    this.onRetry,
    this.onToggleMode,
  });

  /// 当前模式视频是否正在显示
  bool get _isVideoShowing {
    if (streamMode == VideoStreamMode.webrtc) {
      return webrtcConnectionState == WebrtcConnectionState.connected;
    }
    return isP2pConnected && p2pController != null;
  }

  @override
  Widget build(BuildContext context) {
    return ClipRRect( 
      // padding: EdgeInsets.only(top: 15.h,bottom: 35.h,left: 10.w,right: 15.w),
      child: Stack(
        fit: StackFit.expand,
        children: [
          // 视频画面层
          _buildVideoLayer(),
          // 状态指示层
          _buildStatusOverlay(),

          Container(
            decoration: BoxDecoration(
              border: Border.all(color: Color(0xFF010B1D), width: 10.w),
            ),
          ),

          // 边框图片层（中间层，保证按钮可点）
          const Positioned.fill(
            child: Image(
              image: AssetImage('lib/assets/monitoring/box_border.png'),
              fit: BoxFit.fill,
            ),
          ),

          // // 模式切换按钮（右下角倒数第二个位置）
          // if (onToggleMode != null && !isSwitchingMode)
          //   _buildToggleModeButton(),
          
          // 全屏按钮（右下角最后一个位置）
          if (_isVideoShowing) _buildFullscreenButton(context),
          
        ],
      ),
    );
  }

  // ==================== 视频画面层 ====================

  /// 视频画面
  Widget _buildVideoLayer() {
    if (streamMode == VideoStreamMode.webrtc) {
      if (webrtcConnectionState == WebrtcConnectionState.connected &&
          webrtcRenderer != null) {
        return RTCVideoView(
          webrtcRenderer!,
          objectFit: RTCVideoViewObjectFit.RTCVideoViewObjectFitContain,
        );
      }
      return _buildPlaceholder();
    }

    // P2P 模式
    if (isP2pConnected && p2pController != null) {
      return AppPlayerView(controller: p2pController!);
    }
    return _buildPlaceholder();
  }

  // ==================== 状态遮罩层 ====================

  /// 状态遮罩层
  Widget _buildStatusOverlay() {
    if (isSwitchingMode) {
      return _buildSwitchingOverlay();
    }

    if (streamMode == VideoStreamMode.webrtc) {
      switch (webrtcConnectionState) {
        case WebrtcConnectionState.connecting:
          return _buildLoadingOverlay('正在连接摄像头...');
        case WebrtcConnectionState.reconnecting:
          return _buildLoadingOverlay('正在重新连接...');
        case WebrtcConnectionState.failed:
          return _buildErrorOverlay();
        default:
          return const SizedBox.shrink();
      }
    }

    // P2P 模式：未连接显示加载
    if (!isP2pConnected) {
      return _buildLoadingOverlay('正在 P2P 连接...');
    }
    return const SizedBox.shrink();
  }

  /// 模式切换中遮罩
  Widget _buildSwitchingOverlay() {
    return Container(
      color: Colors.black26,
      child: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const CircularProgressIndicator(color: Colors.white70),
            SizedBox(height: 16.h),
            Text(
              '正在切换传输模式...',
              style: TextStyle(fontSize: 18.sp, color: Colors.white70),
            ),
          ],
        ),
      ),
    );
  }

  /// 加载中遮罩
  Widget _buildLoadingOverlay(String message) {
    return Container(
      color: Colors.black26,
      child: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const CircularProgressIndicator(color: Colors.white70),
            SizedBox(height: 16.h),
            Text(
              message,
              style: TextStyle(fontSize: 18.sp, color: Colors.white70),
            ),
          ],
        ),
      ),
    );
  }

  /// 错误遮罩
  Widget _buildErrorOverlay() {
    return Container(
      color: Colors.black38,
      child: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(Icons.error_outline, size: 48.w, color: Colors.white54),
            SizedBox(height: 16.h),
            Text(
              '视频连接失败',
              style: TextStyle(
                fontSize: 20.sp,
                color: Colors.white70,
                fontWeight: FontWeight.w500,
              ),
            ),
            SizedBox(height: 24.h),
            ElevatedButton.icon(
              onPressed: onRetry,
              icon: const Icon(Icons.refresh),
              label: const Text('重新连接'),
              style: ElevatedButton.styleFrom(
                backgroundColor: const Color(0xFF3A87FF),
                foregroundColor: Colors.white,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(20.r),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // ==================== 叠加按钮 ====================

  /// 全屏按钮（右下角）
  Widget _buildFullscreenButton(BuildContext context) {
    return Positioned(
      right: 42.w,
      bottom: 12.h,
      child: GestureDetector(
        onTap: () {
          Navigator.of(context).push(
            MaterialPageRoute(
              builder: (_) => VideoFullscreenPage(
                mode: streamMode,
                webrtcRenderer: webrtcRenderer,
                p2pController: p2pController,
              ),
            ),
          );
        },
        child: Container(
          width: 60.w,
          height: 60.w,
          decoration: BoxDecoration(
            color: Colors.black38,
            borderRadius: BorderRadius.circular(8.r),
          ),
          child: Icon(
            Icons.fullscreen,
            color: Colors.white,
            size: 22.w,
          ),
        ),
      ),
    );
  }

  /// 模式切换按钮（全屏按钮左侧 8px 间距）
  Widget _buildToggleModeButton() {
    return Positioned(
      right: 12.w + 40.w + 68.w,
      bottom: 12.h,
      child: VideoStreamSwitch(
        currentMode: streamMode,
        onToggle: onToggleMode!,
      ),
    );
  }

  /// 未连接时的占位
  Widget _buildPlaceholder() {
    return Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(Icons.videocam_off, size: 48.w, color: Colors.white38),
          SizedBox(height: 16.h),
          // Text(
          //   '暂无视频画面',
          //   style: TextStyle(
          //     fontSize: 20.sp,
          //     color: Colors.white54,
          //     fontWeight: FontWeight.w500,
          //   ),
          // ),
        ],
      ),
    );
  }
}
