import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:intl/intl.dart';
import '../../../../core/services/authorization_service.dart';
import '../../../../core/di/injection_container.dart';

/// 用户资料详情页面
class UserProfilePage extends ConsumerStatefulWidget {
  /// 目标用户的账户序列号
  final String accountSequence;

  /// 用户昵称（用于显示加载中标题）
  final String? nickname;

  const UserProfilePage({
    super.key,
    required this.accountSequence,
    this.nickname,
  });

  /// 导航到用户资料页面
  static Future<void> show(
    BuildContext context, {
    required String accountSequence,
    String? nickname,
  }) {
    return Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => UserProfilePage(
          accountSequence: accountSequence,
          nickname: nickname,
        ),
      ),
    );
  }

  @override
  ConsumerState<UserProfilePage> createState() => _UserProfilePageState();
}

class _UserProfilePageState extends ConsumerState<UserProfilePage> {
  UserProfileResponse? _profile;
  bool _isLoading = true;
  String? _error;
  bool _hasPrivilege = false;

  @override
  void initState() {
    super.initState();
    _loadProfile();
  }

  Future<void> _loadProfile() async {
    setState(() {
      _isLoading = true;
      _error = null;
    });

    try {
      final authService = ref.read(authorizationServiceProvider);

      // 先尝试获取私密资料（如果有权限）
      try {
        final privateProfile = await authService.getUserPrivateProfile(widget.accountSequence);
        if (mounted) {
          setState(() {
            _profile = privateProfile;
            _hasPrivilege = true;
            _isLoading = false;
          });
        }
        return;
      } catch (e) {
        // 没有权限，继续获取公开资料
        debugPrint('无权限获取私密资料，尝试获取公开资料');
      }

      // 获取公开资料
      final profile = await authService.getUserProfile(widget.accountSequence);
      if (mounted) {
        setState(() {
          _profile = profile;
          _hasPrivilege = false;
          _isLoading = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _error = e.toString().replaceAll('Exception: ', '');
          _isLoading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Color(0xFFFFF5E6),
              Color(0xFFFFE4B5),
            ],
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              // 顶部导航栏
              _buildAppBar(),
              // 内容区域
              Expanded(
                child: _isLoading
                    ? _buildLoading()
                    : _error != null
                        ? _buildError()
                        : _buildContent(),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildAppBar() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
      child: Row(
        children: [
          IconButton(
            icon: const Icon(Icons.arrow_back_ios, color: Color(0xFF5D4037)),
            onPressed: () => Navigator.of(context).pop(),
          ),
          Expanded(
            child: Text(
              widget.nickname ?? '用户详情',
              style: const TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.w600,
                color: Color(0xFF5D4037),
              ),
              textAlign: TextAlign.center,
              overflow: TextOverflow.ellipsis,
            ),
          ),
          const SizedBox(width: 48), // 平衡左侧返回按钮
        ],
      ),
    );
  }

  Widget _buildLoading() {
    return const Center(
      child: CircularProgressIndicator(
        valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFD4AF37)),
      ),
    );
  }

  Widget _buildError() {
    return Center(
      child: Padding(
        padding: const EdgeInsets.all(40),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              width: 60,
              height: 60,
              decoration: BoxDecoration(
                color: const Color(0xFFFFF3E0),
                shape: BoxShape.circle,
                border: Border.all(color: const Color(0xFFFFCC80)),
              ),
              child: const Icon(
                Icons.error_outline,
                color: Color(0xFFE65100),
                size: 30,
              ),
            ),
            const SizedBox(height: 16),
            Text(
              _error ?? '加载失败',
              style: const TextStyle(
                fontSize: 14,
                color: Color(0xFF5D4037),
              ),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 20),
            GestureDetector(
              onTap: _loadProfile,
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 10),
                decoration: BoxDecoration(
                  color: const Color(0xFFD4AF37),
                  borderRadius: BorderRadius.circular(20),
                ),
                child: const Text(
                  '重试',
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.white,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildContent() {
    final profile = _profile!;
    return SingleChildScrollView(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 用户头像和基本信息
          _buildUserHeader(profile),
          const SizedBox(height: 16),

          // 统计数据卡片
          _buildStatsCard(profile),
          const SizedBox(height: 16),

          // 基本信息卡片
          _buildInfoCard(
            title: '基本信息',
            children: [
              // _buildInfoRow('用户ID', profile.accountSequence), // 暂时隐藏
              _buildInfoRow('注册时间', _formatDate(profile.registeredAtDateTime)),
              if (profile.inviterNickname != null)
                _buildInfoRow('引荐人', profile.inviterNickname!),
              if (profile.province != null || profile.city != null)
                _buildInfoRow('所在地区', [profile.province, profile.city].whereType<String>().join(' ')),
            ],
          ),
          const SizedBox(height: 16),

          // 授权信息
          if (profile.authorizations.isNotEmpty) ...[
            _buildInfoCard(
              title: '授权信息',
              children: profile.authorizations.map((auth) {
                return _buildAuthorizationRow(auth);
              }).toList(),
            ),
            const SizedBox(height: 16),
          ],

          // 私密信息（仅特权用户可见）
          if (_hasPrivilege && profile.hasPrivateInfo)
            _buildInfoCard(
              title: '联系信息（仅管理员可见）',
              children: [
                if (profile.phoneNumber != null)
                  _buildInfoRow('手机号', profile.phoneNumber!),
                if (profile.email != null)
                  _buildInfoRow('邮箱', profile.email!),
                if (profile.realName != null)
                  _buildInfoRow('真实姓名', profile.realName!),
                if (profile.kycStatus != null)
                  _buildInfoRow('KYC状态', _formatKycStatus(profile.kycStatus!)),
              ],
            ),

          const SizedBox(height: 40),
        ],
      ),
    );
  }

  Widget _buildUserHeader(UserProfileResponse profile) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white.withValues(alpha: 0.9),
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: const Color(0xFFD4AF37).withValues(alpha: 0.1),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Row(
        children: [
          // 头像
          Container(
            width: 72,
            height: 72,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              border: Border.all(
                color: const Color(0xFFD4AF37),
                width: 2,
              ),
              boxShadow: [
                BoxShadow(
                  color: const Color(0xFFD4AF37).withValues(alpha: 0.2),
                  blurRadius: 8,
                  offset: const Offset(0, 2),
                ),
              ],
            ),
            child: ClipOval(
              child: _buildAvatar(profile.avatarUrl, size: 72),
            ),
          ),
          const SizedBox(width: 16),
          // 昵称和标签
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  profile.nickname,
                  style: const TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.w600,
                    color: Color(0xFF5D4037),
                  ),
                ),
                const SizedBox(height: 8),
                Wrap(
                  spacing: 6,
                  runSpacing: 4,
                  children: profile.authorizations.map((auth) {
                    return Container(
                      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
                      decoration: BoxDecoration(
                        color: auth.benefitActive
                            ? const Color(0xFFD4AF37).withValues(alpha: 0.15)
                            : const Color(0xFF9E9E9E).withValues(alpha: 0.15),
                        borderRadius: BorderRadius.circular(10),
                        border: Border.all(
                          color: auth.benefitActive
                              ? const Color(0xFFD4AF37).withValues(alpha: 0.3)
                              : const Color(0xFF9E9E9E).withValues(alpha: 0.3),
                        ),
                      ),
                      child: Text(
                        auth.displayTitle,
                        style: TextStyle(
                          fontSize: 11,
                          color: auth.benefitActive
                              ? const Color(0xFFB8860B)
                              : const Color(0xFF757575),
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    );
                  }).toList(),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildStatsCard(UserProfileResponse profile) {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 12),
      decoration: BoxDecoration(
        color: Colors.white.withValues(alpha: 0.9),
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: const Color(0xFFD4AF37).withValues(alpha: 0.1),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Row(
        children: [
          // --- 以下字段暂时隐藏 ---
          // _buildStatItem(
          //   label: '引荐',
          //   value: '${profile.directReferralCount}',
          //   color: const Color(0xFF4CAF50),
          // ),
          // _buildStatDivider(),
          // _buildStatItem(
          //   label: '同伴',
          //   value: '${profile.umbrellaUserCount}',
          //   color: const Color(0xFF2196F3),
          // ),
          // _buildStatDivider(),
          // _buildStatItem(
          //   label: '本人认种',
          //   value: '${profile.personalPlantingCount}',
          //   color: const Color(0xFF8BC34A),
          // ),
          // _buildStatDivider(),
          // --- 以上字段暂时隐藏 ---
          _buildStatItem(
            label: '同伴认种',
            value: '${profile.teamPlantingCount}',
            color: const Color(0xFFD4AF37),
          ),
        ],
      ),
    );
  }

  Widget _buildStatItem({
    required String label,
    required String value,
    required Color color,
  }) {
    return Expanded(
      child: Column(
        children: [
          Text(
            value,
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: color,
            ),
          ),
          const SizedBox(height: 4),
          Text(
            label,
            style: const TextStyle(
              fontSize: 11,
              color: Color(0xFF8B7355),
            ),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  Widget _buildStatDivider() {
    return Container(
      width: 1,
      height: 36,
      color: const Color(0xFFE0D5C5),
    );
  }

  /// 构建头像 - 支持SVG数据、URL或默认头像
  Widget _buildAvatar(String? avatarUrl, {double size = 64}) {
    if (avatarUrl == null || avatarUrl.isEmpty) {
      return _buildDefaultAvatar(size: size);
    }

    // 检测是否是SVG字符串
    if (avatarUrl.contains('<svg') || avatarUrl.startsWith('<?xml')) {
      return SvgPicture.string(
        avatarUrl,
        width: size,
        height: size,
        fit: BoxFit.cover,
      );
    }

    // 否则尝试作为URL加载
    return Image.network(
      avatarUrl,
      width: size,
      height: size,
      fit: BoxFit.cover,
      errorBuilder: (context, error, stackTrace) => _buildDefaultAvatar(size: size),
    );
  }

  Widget _buildDefaultAvatar({double size = 64}) {
    return Container(
      width: size,
      height: size,
      color: const Color(0xFFFFF5E6),
      child: Icon(
        Icons.person,
        size: size * 0.5,
        color: const Color(0xFFD4AF37),
      ),
    );
  }

  Widget _buildInfoCard({
    required String title,
    required List<Widget> children,
  }) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white.withValues(alpha: 0.9),
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: const Color(0xFFD4AF37).withValues(alpha: 0.1),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            title,
            style: const TextStyle(
              fontSize: 15,
              fontWeight: FontWeight.w600,
              color: Color(0xFF5D4037),
            ),
          ),
          const SizedBox(height: 12),
          ...children,
        ],
      ),
    );
  }

  Widget _buildInfoRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 10),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 80,
            child: Text(
              label,
              style: const TextStyle(
                fontSize: 13,
                color: Color(0xFF8B7355),
              ),
            ),
          ),
          Expanded(
            child: Text(
              value,
              style: const TextStyle(
                fontSize: 13,
                color: Color(0xFF5D4037),
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildAuthorizationRow(UserAuthorizationInfo auth) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 10),
      child: Row(
        children: [
          Container(
            width: 8,
            height: 8,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              color: auth.benefitActive ? const Color(0xFF4CAF50) : const Color(0xFF9E9E9E),
            ),
          ),
          const SizedBox(width: 10),
          Expanded(
            child: Text(
              auth.displayTitle,
              style: const TextStyle(
                fontSize: 13,
                color: Color(0xFF5D4037),
              ),
            ),
          ),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
            decoration: BoxDecoration(
              color: auth.benefitActive
                  ? const Color(0xFF4CAF50).withValues(alpha: 0.1)
                  : const Color(0xFF9E9E9E).withValues(alpha: 0.1),
              borderRadius: BorderRadius.circular(10),
            ),
            child: Text(
              auth.benefitActive ? '权益已激活' : '权益未激活',
              style: TextStyle(
                fontSize: 11,
                color: auth.benefitActive ? const Color(0xFF4CAF50) : const Color(0xFF9E9E9E),
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        ],
      ),
    );
  }

  String _formatDate(DateTime date) {
    return DateFormat('yyyy-MM-dd').format(date);
  }

  String _formatKycStatus(String status) {
    switch (status.toUpperCase()) {
      case 'VERIFIED':
        return '已认证';
      case 'PENDING':
        return '审核中';
      case 'REJECTED':
        return '已拒绝';
      default:
        return '未认证';
    }
  }
}

/// 为了向后兼容，保留 UserProfileDialog 作为别名
/// @deprecated 请使用 UserProfilePage.show() 替代
class UserProfileDialog {
  /// 显示用户资料页面
  static Future<void> show(
    BuildContext context, {
    required String accountSequence,
    String? nickname,
  }) {
    return UserProfilePage.show(
      context,
      accountSequence: accountSequence,
      nickname: nickname,
    );
  }
}
