import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../providers/user_providers.dart';
import '../../../data/models/capability_model.dart';

class EditProfilePage extends ConsumerStatefulWidget {
  const EditProfilePage({super.key});

  @override
  ConsumerState<EditProfilePage> createState() => _EditProfilePageState();
}

class _EditProfilePageState extends ConsumerState<EditProfilePage> {
  static const Color _orange = Color(0xFFFF6B00);
  static const Color _green = Color(0xFF10B981);
  static const Color _darkText = Color(0xFF1F2937);
  static const Color _grayText = Color(0xFF6B7280);
  static const Color _bgGray = Color(0xFFF3F4F6);

  late TextEditingController _nicknameController;
  int _selectedAvatarIndex = 0;
  bool _isLoading = false;

  // 预设头像颜色列表
  static const List<Color> _avatarColors = [
    Color(0xFFFF6B00), // 橙色
    Color(0xFF10B981), // 绿色
    Color(0xFF3B82F6), // 蓝色
    Color(0xFFEF4444), // 红色
    Color(0xFF8B5CF6), // 紫色
    Color(0xFFF59E0B), // 琥珀色
    Color(0xFFEC4899), // 粉色
    Color(0xFF06B6D4), // 青色
  ];

  @override
  void initState() {
    super.initState();
    final user = ref.read(userNotifierProvider);
    _nicknameController = TextEditingController(text: user.nickname ?? '');
    _selectedAvatarIndex = user.avatarIndex;
  }

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

  @override
  Widget build(BuildContext context) {
    final user = ref.watch(userNotifierProvider);

    return Scaffold(
      backgroundColor: _bgGray,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: _darkText),
          onPressed: () => context.pop(),
        ),
        title: const Text(
          '编辑资料',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
            color: _darkText,
          ),
        ),
        centerTitle: true,
        actions: [
          TextButton(
            onPressed: _isLoading ? null : _saveProfile,
            child: Text(
              '保存',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w500,
                color: _isLoading ? _grayText : _orange,
              ),
            ),
          ),
        ],
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            const SizedBox(height: 24),

            // 头像选择区域
            _buildAvatarSection(user),

            const SizedBox(height: 32),

            // 昵称输入区域
            _buildNicknameSection(),

            const SizedBox(height: 16),

            // 用户信息展示（只读）
            _buildInfoSection(user),
          ],
        ),
      ),
    );
  }

  Widget _buildAvatarSection(UserState user) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '选择头像',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: _darkText,
            ),
          ),
          const SizedBox(height: 20),

          // 当前头像预览
          Center(
            child: Container(
              width: 100,
              height: 100,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                gradient: LinearGradient(
                  colors: [
                    _avatarColors[_selectedAvatarIndex].withValues(alpha: 0.8),
                    _avatarColors[_selectedAvatarIndex],
                  ],
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                ),
                boxShadow: [
                  BoxShadow(
                    color: _avatarColors[_selectedAvatarIndex].withValues(alpha: 0.3),
                    blurRadius: 12,
                    offset: const Offset(0, 4),
                  ),
                ],
              ),
              child: Center(
                child: Text(
                  _getAvatarText(user),
                  style: const TextStyle(
                    fontSize: 42,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ),

          const SizedBox(height: 24),

          // 头像颜色选择网格
          GridView.builder(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 4,
              crossAxisSpacing: 16,
              mainAxisSpacing: 16,
            ),
            itemCount: _avatarColors.length,
            itemBuilder: (context, index) {
              final isSelected = _selectedAvatarIndex == index;
              return GestureDetector(
                onTap: () {
                  setState(() {
                    _selectedAvatarIndex = index;
                  });
                },
                child: Container(
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    gradient: LinearGradient(
                      colors: [
                        _avatarColors[index].withValues(alpha: 0.8),
                        _avatarColors[index],
                      ],
                      begin: Alignment.topLeft,
                      end: Alignment.bottomRight,
                    ),
                    border: isSelected
                        ? Border.all(color: _darkText, width: 3)
                        : null,
                    boxShadow: isSelected
                        ? [
                            BoxShadow(
                              color: _avatarColors[index].withValues(alpha: 0.4),
                              blurRadius: 8,
                              offset: const Offset(0, 2),
                            ),
                          ]
                        : null,
                  ),
                  child: isSelected
                      ? const Icon(Icons.check, color: Colors.white, size: 28)
                      : null,
                ),
              );
            },
          ),
        ],
      ),
    );
  }

  Widget _buildNicknameSection() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '昵称',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: _darkText,
            ),
          ),
          const SizedBox(height: 12),
          TextField(
            controller: _nicknameController,
            maxLength: 20,
            decoration: InputDecoration(
              hintText: '请输入昵称',
              hintStyle: const TextStyle(color: _grayText),
              filled: true,
              fillColor: _bgGray,
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(12),
                borderSide: BorderSide.none,
              ),
              focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(12),
                borderSide: const BorderSide(color: _orange, width: 2),
              ),
              counterStyle: const TextStyle(color: _grayText),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildInfoSection(UserState user) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '账户信息',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: _darkText,
            ),
          ),
          const SizedBox(height: 16),
          _buildInfoItem('手机号', user.phone ?? '--'),
          const Divider(height: 24),
          _buildInfoItem('实名状态', user.isKycVerified ? '已实名' : '未实名',
              valueColor: user.isKycVerified ? _green : _grayText),
          if (user.realName != null && user.realName!.isNotEmpty) ...[
            const Divider(height: 24),
            _buildInfoItem('真实姓名', _maskName(user.realName!)),
          ],
        ],
      ),
    );
  }

  Widget _buildInfoItem(String label, String value, {Color? valueColor}) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          label,
          style: const TextStyle(
            fontSize: 14,
            color: _grayText,
          ),
        ),
        Text(
          value,
          style: TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w500,
            color: valueColor ?? _darkText,
          ),
        ),
      ],
    );
  }

  String _getAvatarText(UserState user) {
    final nickname = _nicknameController.text;
    if (nickname.isNotEmpty) {
      return nickname.substring(0, 1).toUpperCase();
    }
    if (user.realName?.isNotEmpty == true) {
      return user.realName!.substring(0, 1).toUpperCase();
    }
    return 'U';
  }

  String _maskName(String name) {
    if (name.length <= 1) return name;
    return '${name.substring(0, 1)}${'*' * (name.length - 1)}';
  }

  Future<void> _saveProfile() async {
    final capabilities = ref.read(capabilitiesProvider).valueOrNull ?? CapabilityMap.defaultAll();
    if (!capabilities.profileEditEnabled) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('您的编辑资料功能已被限制'),
          backgroundColor: Color(0xFFEF4444),
        ),
      );
      return;
    }

    setState(() {
      _isLoading = true;
    });

    try {
      final notifier = ref.read(userNotifierProvider.notifier);

      // 保存头像
      await notifier.updateAvatar(_selectedAvatarIndex);

      // 保存昵称
      final nickname = _nicknameController.text.trim();
      if (nickname.isNotEmpty) {
        await notifier.updateNickname(nickname);
      }

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('保存成功'),
            backgroundColor: _green,
          ),
        );
        context.pop();
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('保存失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }
}
