import 'package:flutter/material.dart';
import 'package:lottie/lottie.dart';
import 'user_profile_dialog.dart';

/// 火柴人排名数据模型
class StickmanRankingData {
  final String id;
  final String nickname;
  final String? avatarUrl;
  final int completedCount; // 完成数量
  final int targetCount; // 目标数量 (省: 50000, 市: 10000)
  final double monthlyEarnings; // 本月可结算收益
  final bool isCurrentUser; // 是否是当前用户
  final String? accountSequence; // 账户序列号（用于查看详情）

  StickmanRankingData({
    required this.id,
    required this.nickname,
    this.avatarUrl,
    required this.completedCount,
    required this.targetCount,
    required this.monthlyEarnings,
    this.isCurrentUser = false,
    this.accountSequence,
  });

  /// 完成进度 (0.0 - 1.0)
  double get progress => (completedCount / targetCount).clamp(0.0, 1.0);
}

/// 授权类型
enum AuthorizationRoleType {
  province, // 省公司 (目标: 5万)
  city, // 市公司 (目标: 1万)
}

/// 火柴人赛跑排名组件
class StickmanRaceWidget extends StatefulWidget {
  final List<StickmanRankingData> rankings;
  final AuthorizationRoleType roleType;
  final String regionName; // 省/市名称

  const StickmanRaceWidget({
    super.key,
    required this.rankings,
    required this.roleType,
    required this.regionName,
  });

  @override
  State<StickmanRaceWidget> createState() => _StickmanRaceWidgetState();
}

class _StickmanRaceWidgetState extends State<StickmanRaceWidget>
    with TickerProviderStateMixin {
  late AnimationController _bounceController;

  @override
  void initState() {
    super.initState();
    // 用于火柴人上下弹跳效果
    _bounceController = AnimationController(
      duration: const Duration(milliseconds: 500),
      vsync: this,
    )..repeat(reverse: true);
  }

  @override
  void dispose() {
    _bounceController.dispose();
    super.dispose();
  }

  /// 获取目标数量
  int get targetCount =>
      widget.roleType == AuthorizationRoleType.province ? 50000 : 10000;

  /// 获取目标文本
  String get targetText =>
      widget.roleType == AuthorizationRoleType.province ? '5万' : '1万';

  @override
  Widget build(BuildContext context) {
    if (widget.rankings.isEmpty) {
      return const SizedBox.shrink();
    }

    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: const Color(0x80FFFFFF),
        borderRadius: BorderRadius.circular(16),
        border: Border.all(
          color: const Color(0x33D4AF37),
          width: 1,
        ),
        boxShadow: const [
          BoxShadow(
            color: Color(0x1A000000),
            blurRadius: 8,
            offset: Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题行
          _buildHeader(),
          const SizedBox(height: 16),

          // 赛道区域
          _buildRaceTrack(),
          const SizedBox(height: 12),

          // 进度条和目标
          _buildProgressBar(),
          const SizedBox(height: 16),

          // 排名列表
          _buildRankingList(),
        ],
      ),
    );
  }

  /// 构建标题
  Widget _buildHeader() {
    final roleText =
        widget.roleType == AuthorizationRoleType.province ? '省公司' : '市公司';
    return Row(
      children: [
        Container(
          width: 4,
          height: 20,
          decoration: BoxDecoration(
            color: const Color(0xFFD4AF37),
            borderRadius: BorderRadius.circular(2),
          ),
        ),
        const SizedBox(width: 8),
        Text(
          '${widget.regionName}$roleText排名',
          style: const TextStyle(
            fontSize: 16,
            fontFamily: 'Inter',
            fontWeight: FontWeight.w600,
            color: Color(0xFF5D4037),
          ),
        ),
        const Spacer(),
        Text(
          '目标: $targetText棵',
          style: const TextStyle(
            fontSize: 12,
            fontFamily: 'Inter',
            color: Color(0xFF8B5A2B),
          ),
        ),
      ],
    );
  }

  /// 每个火柴人需要的最小高度（标签+动画+昵称+间距）
  static const double _minTrackHeight = 100.0;

  /// 构建赛道区域
  Widget _buildRaceTrack() {
    // 按完成数量排序
    final sortedRankings = List<StickmanRankingData>.from(widget.rankings)
      ..sort((a, b) => b.completedCount.compareTo(a.completedCount));

    // 根据火柴人数量动态计算赛道高度（无上限）
    final trackCount = sortedRankings.length;
    final raceTrackHeight = (trackCount * _minTrackHeight).clamp(160.0, double.infinity);

    // 计算每个跑道的高度和位置
    final usableHeight = raceTrackHeight - 40;
    final trackHeight = usableHeight / trackCount;

    return SizedBox(
      height: raceTrackHeight,
      child: Stack(
        children: [
          // 背景赛道线
          Positioned.fill(
            child: CustomPaint(
              painter: _TrackPainter(
                trackCount: sortedRankings.length,
              ),
            ),
          ),

          // 每个跑道的终点红旗
          ...List.generate(trackCount, (index) {
            final verticalPosition = index * trackHeight + 10 + trackHeight / 2 - 16;
            return Positioned(
              right: 8,
              top: verticalPosition,
              child: const Icon(
                Icons.flag,
                color: Colors.red,
                size: 24,
              ),
            );
          }),

          // 火柴人们
          ...sortedRankings.asMap().entries.map((entry) {
            final index = entry.key;
            final data = entry.value;
            return _buildStickman(data, index, sortedRankings.length, raceTrackHeight);
          }),
        ],
      ),
    );
  }

  /// 构建单个火柴人
  Widget _buildStickman(StickmanRankingData data, int rank, int total, double raceTrackHeight) {
    // 计算水平位置 (根据进度)
    final horizontalProgress = data.progress;

    // 计算垂直位置 (不同排名在不同跑道)
    // 预留顶部和底部空间
    final usableHeight = raceTrackHeight - 40;
    final trackHeight = usableHeight / total;
    final verticalPosition = rank * trackHeight + 10;

    debugPrint('[StickmanRace] _buildStickman() - rank=$rank, total=$total, progress=$horizontalProgress');

    return AnimatedBuilder(
      animation: _bounceController,
      builder: (context, child) {
        // 添加上下弹跳效果
        final bounce = _bounceController.value * 3;

        // 计算可用宽度：屏幕宽度 - 页面padding(32) - 容器padding(32) - 红旗区域(40) - 火柴人宽度一半(30)
        // 让火柴人在100%时正好到达红旗位置
        final screenWidth = MediaQuery.of(context).size.width;
        final containerWidth = screenWidth - 32 - 32; // 页面padding + 容器padding
        final stickmanHalfWidth = 30.0; // 火柴人宽度的一半，用于居中对齐
        final flagAreaWidth = 40.0; // 红旗区域宽度（红旗在right:8位置，图标24+边距）
        final nicknameAreaWidth = 65.0; // 昵称区域宽度
        // 确保可用宽度不为负数
        final rawAvailableWidth = containerWidth - flagAreaWidth - stickmanHalfWidth - nicknameAreaWidth;
        final availableWidth = rawAvailableWidth.clamp(60.0, double.infinity);
        final leftPosition = nicknameAreaWidth + availableWidth * horizontalProgress;
        final stickmanBoxWidth = leftPosition - nicknameAreaWidth + stickmanHalfWidth * 2;

        debugPrint('[StickmanRace] Layout: screenWidth=$screenWidth, containerWidth=$containerWidth, rawAvailableWidth=$rawAvailableWidth, availableWidth=$availableWidth, leftPosition=$leftPosition, stickmanBoxWidth=$stickmanBoxWidth');

        return Positioned(
          left: 0,
          top: verticalPosition - bounce,
          child: Row(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start, // 顶部对齐，昵称和数量标签高度相同，自然中心对齐
            children: [
              // 昵称标签 - 与数量标签顶部对齐（两者高度相近，实现中心对齐）
              SizedBox(
                width: nicknameAreaWidth,
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2),
                  decoration: BoxDecoration(
                    color: data.isCurrentUser
                        ? const Color(0xFFD4AF37).withValues(alpha: 0.2)
                        : Colors.white.withValues(alpha: 0.8),
                    borderRadius: BorderRadius.circular(4),
                    border: data.isCurrentUser
                        ? Border.all(color: const Color(0xFFD4AF37), width: 1)
                        : null,
                  ),
                  child: Text(
                    data.nickname,
                    style: TextStyle(
                      fontSize: 9,
                      fontFamily: 'Inter',
                      fontWeight:
                          data.isCurrentUser ? FontWeight.w600 : FontWeight.w400,
                      color: data.isCurrentUser
                          ? const Color(0xFFD4AF37)
                          : const Color(0xFF5D4037),
                    ),
                    overflow: TextOverflow.ellipsis,
                    textAlign: TextAlign.center,
                  ),
                ),
              ),
              // 火柴人和数量标签
              SizedBox(
                width: stickmanBoxWidth.clamp(60.0, double.infinity),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        // 完成数量标签
                        Container(
                          constraints: const BoxConstraints(maxWidth: 60),
                          padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                          decoration: BoxDecoration(
                            color: data.isCurrentUser
                                ? const Color(0xFFD4AF37)
                                : const Color(0xFF8B5A2B),
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: FittedBox(
                            fit: BoxFit.scaleDown,
                            child: Text(
                              '${_formatNumber(data.completedCount)}棵',
                              style: const TextStyle(
                                fontSize: 9,
                                fontFamily: 'Inter',
                                fontWeight: FontWeight.w600,
                                color: Colors.white,
                              ),
                            ),
                          ),
                        ),
                        const SizedBox(height: 2),
                        // 火柴人动画
                        RunningStickman(
                          size: 36,
                          color: data.isCurrentUser
                              ? const Color(0xFFD4AF37)
                              : const Color(0xFF5D4037),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  /// 构建进度条
  Widget _buildProgressBar() {
    // 找出领先者的进度
    final maxProgress = widget.rankings.isEmpty
        ? 0.0
        : widget.rankings
            .map((r) => r.progress)
            .reduce((a, b) => a > b ? a : b);

    return Column(
      children: [
        // 进度条
        Container(
          height: 8,
          decoration: BoxDecoration(
            color: const Color(0xFFE0E0E0),
            borderRadius: BorderRadius.circular(4),
          ),
          child: Stack(
            children: [
              // 进度填充
              FractionallySizedBox(
                widthFactor: maxProgress,
                child: Container(
                  decoration: BoxDecoration(
                    gradient: const LinearGradient(
                      colors: [Color(0xFFD4AF37), Color(0xFFF5D799)],
                    ),
                    borderRadius: BorderRadius.circular(4),
                  ),
                ),
              ),
            ],
          ),
        ),
        const SizedBox(height: 4),
        // 进度标签
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            const Text(
              '0',
              style: TextStyle(
                fontSize: 10,
                fontFamily: 'Inter',
                color: Color(0xFF8B5A2B),
              ),
            ),
            Text(
              targetText,
              style: const TextStyle(
                fontSize: 10,
                fontFamily: 'Inter',
                color: Color(0xFF8B5A2B),
              ),
            ),
          ],
        ),
      ],
    );
  }

  /// 构建排名列表
  Widget _buildRankingList() {
    // 按完成数量排序
    final sortedRankings = List<StickmanRankingData>.from(widget.rankings)
      ..sort((a, b) => b.completedCount.compareTo(a.completedCount));

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '排名详情',
          style: TextStyle(
            fontSize: 14,
            fontFamily: 'Inter',
            fontWeight: FontWeight.w500,
            color: Color(0xFF5D4037),
          ),
        ),
        const SizedBox(height: 8),
        ...sortedRankings.asMap().entries.map((entry) {
          final rank = entry.key + 1;
          final data = entry.value;
          return _buildRankingItem(rank, data);
        }),
      ],
    );
  }

  /// 构建排名项
  Widget _buildRankingItem(int rank, StickmanRankingData data) {
    return GestureDetector(
      onTap: () => _showUserProfile(data),
      child: Container(
        margin: const EdgeInsets.only(bottom: 8),
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: data.isCurrentUser
              ? const Color(0xFFD4AF37).withValues(alpha: 0.1)
              : Colors.white.withValues(alpha: 0.5),
          borderRadius: BorderRadius.circular(8),
          border: data.isCurrentUser
              ? Border.all(color: const Color(0xFFD4AF37), width: 1)
              : null,
        ),
        child: Row(
        children: [
          // 排名
          Container(
            width: 28,
            height: 28,
            decoration: BoxDecoration(
              color: _getRankColor(rank),
              shape: BoxShape.circle,
            ),
            child: Center(
              child: Text(
                '$rank',
                style: const TextStyle(
                  fontSize: 14,
                  fontFamily: 'Inter',
                  fontWeight: FontWeight.w700,
                  color: Colors.white,
                ),
              ),
            ),
          ),
          const SizedBox(width: 12),

          // 昵称
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Text(
                      data.nickname,
                      style: TextStyle(
                        fontSize: 14,
                        fontFamily: 'Inter',
                        fontWeight: data.isCurrentUser
                            ? FontWeight.w600
                            : FontWeight.w500,
                        color: const Color(0xFF5D4037),
                      ),
                    ),
                    if (data.isCurrentUser) ...[
                      const SizedBox(width: 4),
                      Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 4,
                          vertical: 1,
                        ),
                        decoration: BoxDecoration(
                          color: const Color(0xFFD4AF37),
                          borderRadius: BorderRadius.circular(4),
                        ),
                        child: const Text(
                          '我',
                          style: TextStyle(
                            fontSize: 9,
                            fontFamily: 'Inter',
                            fontWeight: FontWeight.w600,
                            color: Colors.white,
                          ),
                        ),
                      ),
                    ],
                  ],
                ),
                const SizedBox(height: 2),
                FittedBox(
                  fit: BoxFit.scaleDown,
                  alignment: Alignment.centerLeft,
                  child: Text(
                    '本月收益: ${_formatCurrency(data.monthlyEarnings)} 绿积分',
                    style: const TextStyle(
                      fontSize: 11,
                      fontFamily: 'Inter',
                      color: Color(0xFF8B5A2B),
                    ),
                  ),
                ),
              ],
            ),
          ),

          // 完成数量和进度
          ConstrainedBox(
            constraints: const BoxConstraints(maxWidth: 100),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                FittedBox(
                  fit: BoxFit.scaleDown,
                  alignment: Alignment.centerRight,
                  child: Text(
                    '${_formatNumber(data.completedCount)}棵',
                    style: const TextStyle(
                      fontSize: 16,
                      fontFamily: 'Inter',
                      fontWeight: FontWeight.w700,
                      color: Color(0xFFD4AF37),
                    ),
                  ),
                ),
                const SizedBox(height: 2),
                FittedBox(
                  fit: BoxFit.scaleDown,
                  alignment: Alignment.centerRight,
                  child: Text(
                    '${(data.progress * 100).toStringAsFixed(1)}%',
                    style: const TextStyle(
                      fontSize: 11,
                      fontFamily: 'Inter',
                      color: Color(0xFF8B5A2B),
                    ),
                  ),
                ),
              ],
            ),
          ),
          // 点击查看详情图标
          const SizedBox(width: 8),
          const Icon(
            Icons.chevron_right,
            color: Color(0xFF8B5A2B),
            size: 20,
          ),
        ],
      ),
      ),
    );
  }

  /// 显示用户资料弹窗
  void _showUserProfile(StickmanRankingData data) {
    if (data.accountSequence == null || data.accountSequence!.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: const Row(
            children: [
              Icon(
                Icons.info_outline,
                color: Colors.white,
                size: 18,
              ),
              SizedBox(width: 8),
              Text(
                '暂无该用户的详细信息',
                style: TextStyle(
                  fontFamily: 'Inter',
                  fontSize: 14,
                  color: Colors.white,
                ),
              ),
            ],
          ),
          backgroundColor: const Color(0xFF8B5A2B),
          behavior: SnackBarBehavior.floating,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
          margin: const EdgeInsets.all(16),
          duration: const Duration(seconds: 2),
        ),
      );
      return;
    }

    UserProfileDialog.show(
      context,
      accountSequence: data.accountSequence!,
      nickname: data.nickname,
    );
  }

  /// 获取排名颜色
  Color _getRankColor(int rank) {
    switch (rank) {
      case 1:
        return const Color(0xFFFFD700); // 金色
      case 2:
        return const Color(0xFFC0C0C0); // 银色
      case 3:
        return const Color(0xFFCD7F32); // 铜色
      default:
        return const Color(0xFF8B5A2B);
    }
  }

  /// 格式化数字
  String _formatNumber(int number) {
    if (number >= 10000) {
      return '${(number / 10000).toStringAsFixed(1)}万';
    }
    return number.toString();
  }

  /// 格式化货币
  String _formatCurrency(double amount) {
    if (amount >= 10000) {
      return '${(amount / 10000).toStringAsFixed(2)}万';
    }
    return amount.toStringAsFixed(2);
  }
}

/// 赛道绘制器
class _TrackPainter extends CustomPainter {
  final int trackCount;

  _TrackPainter({required this.trackCount});

  @override
  void paint(Canvas canvas, Size size) {
    final dashedPaint = Paint()
      ..color = const Color(0xFFBDBDBD)
      ..strokeWidth = 1
      ..style = PaintingStyle.stroke;

    final trackHeight = (size.height - 40) / trackCount;

    for (int i = 0; i < trackCount; i++) {
      final y = 20 + i * trackHeight + trackHeight / 2;

      // 绘制虚线跑道
      double startX = 0;
      const dashWidth = 10.0;
      const dashSpace = 5.0;

      while (startX < size.width) {
        canvas.drawLine(
          Offset(startX, y),
          Offset(startX + dashWidth, y),
          dashedPaint,
        );
        startX += dashWidth + dashSpace;
      }
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}

/// 跑步火柴人动画组件 - 使用 Lottie 动画
class RunningStickman extends StatelessWidget {
  final double size;
  final Color color;

  const RunningStickman({
    super.key,
    this.size = 40,
    this.color = Colors.black,
  });

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: size,
      height: size * 1.2,
      child: ColorFiltered(
        colorFilter: ColorFilter.mode(
          color,
          BlendMode.srcIn,
        ),
        child: Lottie.asset(
          'assets/lottie/stickman_runner.json',
          fit: BoxFit.contain,
          repeat: true,
        ),
      ),
    );
  }
}
