import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:go_router/go_router.dart';
import 'package:image_picker/image_picker.dart';
import '../../../../core/di/injection_container.dart';

/// 编辑资料页面 - 允许用户修改头像和昵称
/// 包含头像选择底部弹窗（拍照、从相册选择、删除头像）
class EditProfilePage extends ConsumerStatefulWidget {
  const EditProfilePage({super.key});

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

class _EditProfilePageState extends ConsumerState<EditProfilePage> {
  // 昵称控制器
  final TextEditingController _nicknameController = TextEditingController();

  // 图片选择器
  final ImagePicker _imagePicker = ImagePicker();

  // 当前头像SVG（初始生成的头像）
  String? _avatarSvg;

  // 当前头像URL（用户上传的头像）
  String? _avatarUrl;

  // 本地选择的图片文件（待上传）
  File? _selectedImageFile;

  // 原始昵称（用于判断是否修改）
  String? _originalNickname;

  // 是否正在保存
  bool _isSaving = false;

  // 是否正在加载
  bool _isLoading = true;

  // 是否正在上传头像
  bool _isUploadingAvatar = false;

  // 是否有数据变更（用于返回时通知上一页刷新）
  bool _hasChanges = false;

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

  /// 加载用户数据
  Future<void> _loadUserData() async {
    final accountService = ref.read(accountServiceProvider);

    final username = await accountService.getUsername();
    final avatarSvg = await accountService.getAvatarSvg();
    final avatarUrl = await accountService.getAvatarUrl();

    if (mounted) {
      setState(() {
        _nicknameController.text = username ?? '';
        _originalNickname = username;
        _avatarSvg = avatarSvg;
        _avatarUrl = avatarUrl;
        _isLoading = false;
      });
    }
  }

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

  /// 返回上一页
  void _goBack() {
    context.pop(_hasChanges);
  }

  /// 显示头像选择底部弹窗
  void _showAvatarPicker() {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      builder: (context) => _buildAvatarPickerSheet(),
    );
  }

  /// 拍照
  Future<void> _takePhoto() async {
    Navigator.pop(context);

    try {
      final XFile? image = await _imagePicker.pickImage(
        source: ImageSource.camera,
        maxWidth: 512,
        maxHeight: 512,
        imageQuality: 85,
      );

      if (image != null && mounted) {
        setState(() {
          _selectedImageFile = File(image.path);
        });
        // 立即上传头像
        await _uploadSelectedAvatar();
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('拍照失败: ${e.toString()}'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  /// 从相册选择
  Future<void> _pickFromGallery() async {
    Navigator.pop(context);

    try {
      final XFile? image = await _imagePicker.pickImage(
        source: ImageSource.gallery,
        maxWidth: 512,
        maxHeight: 512,
        imageQuality: 85,
      );

      if (image != null && mounted) {
        setState(() {
          _selectedImageFile = File(image.path);
        });
        // 立即上传头像
        await _uploadSelectedAvatar();
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('选择图片失败: ${e.toString()}'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  /// 上传选中的头像
  Future<void> _uploadSelectedAvatar() async {
    if (_selectedImageFile == null) return;

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

    try {
      final accountService = ref.read(accountServiceProvider);
      final newAvatarUrl = await accountService.uploadAvatar(_selectedImageFile!);

      if (mounted) {
        setState(() {
          _avatarUrl = newAvatarUrl;
          _selectedImageFile = null; // 清除本地文件引用
          _isUploadingAvatar = false;
          _hasChanges = true; // 标记有变更
        });

        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('头像上传成功'),
            backgroundColor: Color(0xFFD4AF37),
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        setState(() {
          _selectedImageFile = null;
          _isUploadingAvatar = false;
        });

        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('头像上传失败: ${e.toString().replaceAll('Exception: ', '')}'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  /// 删除头像（恢复默认SVG头像）
  void _deleteAvatar() {
    Navigator.pop(context);
    setState(() {
      _avatarUrl = null;
      _selectedImageFile = null;
    });
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text('已恢复默认头像'),
        backgroundColor: Color(0xFFD4AF37),
      ),
    );
  }

  /// 取消选择
  void _cancelPicker() {
    Navigator.pop(context);
  }

  /// 保存资料
  Future<void> _saveProfile() async {
    final newNickname = _nicknameController.text.trim();

    if (newNickname.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('昵称不能为空'),
          backgroundColor: Colors.red,
        ),
      );
      return;
    }

    // 检查是否有修改
    final nicknameChanged = newNickname != _originalNickname;
    if (!nicknameChanged) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('未做任何修改'),
          backgroundColor: Color(0xFFD4AF37),
        ),
      );
      return;
    }

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

    try {
      final accountService = ref.read(accountServiceProvider);

      // 调用API更新资料
      await accountService.updateProfile(
        nickname: nicknameChanged ? newNickname : null,
      );

      if (!mounted) return;

      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('保存成功'),
          backgroundColor: Color(0xFFD4AF37),
        ),
      );

      context.pop(true); // 返回 true 表示有更新
    } catch (e) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('保存失败: ${e.toString().replaceAll('Exception: ', '')}'),
          backgroundColor: Colors.red,
        ),
      );
    } finally {
      if (mounted) {
        setState(() {
          _isSaving = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      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
                    ? const Center(
                        child: CircularProgressIndicator(
                          valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFD4AF37)),
                        ),
                      )
                    : SingleChildScrollView(
                        child: Column(
                          children: [
                            const SizedBox(height: 40),
                            // 头像区域
                            _buildAvatarSection(),
                            const SizedBox(height: 40),
                            // 昵称输入区域
                            _buildNicknameSection(),
                          ],
                        ),
                      ),
              ),
              // 底部保存按钮
              _buildSaveButton(),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建顶部导航栏
  Widget _buildAppBar() {
    return Container(
      height: 64,
      padding: const EdgeInsets.only(top: 16, left: 16, right: 16),
      child: Row(
        children: [
          // 返回按钮
          GestureDetector(
            onTap: _goBack,
            child: Container(
              width: 48,
              height: 48,
              alignment: Alignment.center,
              child: const Icon(
                Icons.arrow_back,
                size: 24,
                color: Color(0xFF5D4037),
              ),
            ),
          ),
          // 标题
          Expanded(
            child: Text(
              '编辑资料',
              style: const TextStyle(
                fontSize: 18,
                fontFamily: 'Inter',
                fontWeight: FontWeight.w500,
                height: 1.25,
                letterSpacing: -0.27,
                color: Color(0xFF5D4037),
              ),
              textAlign: TextAlign.center,
            ),
          ),
          // 占位（保持标题居中）
          const SizedBox(width: 48),
        ],
      ),
    );
  }

  /// 构建头像区域
  Widget _buildAvatarSection() {
    return GestureDetector(
      onTap: _isUploadingAvatar ? null : _showAvatarPicker,
      child: Column(
        children: [
          // 头像
          Stack(
            children: [
              Container(
                width: 128,
                height: 128,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: const Color(0xFFFFF5E6),
                  border: Border.all(
                    color: const Color(0x33D4AF37),
                    width: 2,
                  ),
                ),
                child: ClipOval(
                  child: _buildAvatarContent(),
                ),
              ),
              // 上传中的loading指示器
              if (_isUploadingAvatar)
                Positioned.fill(
                  child: Container(
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: Colors.black.withOpacity(0.5),
                    ),
                    child: const Center(
                      child: CircularProgressIndicator(
                        valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                        strokeWidth: 3,
                      ),
                    ),
                  ),
                ),
            ],
          ),
          const SizedBox(height: 16),
          // 修改头像文字
          Text(
            _isUploadingAvatar ? '上传中...' : '修改头像',
            style: const TextStyle(
              fontSize: 16,
              fontFamily: 'Inter',
              fontWeight: FontWeight.w500,
              height: 1.5,
              color: Color(0xFF8B5A2B),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建头像内容（支持本地文件、网络URL、SVG）
  Widget _buildAvatarContent() {
    // 优先显示本地选中的图片（正在上传中）
    if (_selectedImageFile != null) {
      return Image.file(
        _selectedImageFile!,
        width: 128,
        height: 128,
        fit: BoxFit.cover,
      );
    }

    // 其次显示已上传的网络图片URL
    if (_avatarUrl != null && _avatarUrl!.isNotEmpty) {
      return Image.network(
        _avatarUrl!,
        width: 128,
        height: 128,
        fit: BoxFit.cover,
        loadingBuilder: (context, child, loadingProgress) {
          if (loadingProgress == null) return child;
          return Center(
            child: CircularProgressIndicator(
              value: loadingProgress.expectedTotalBytes != null
                  ? loadingProgress.cumulativeBytesLoaded /
                      loadingProgress.expectedTotalBytes!
                  : null,
              valueColor: const AlwaysStoppedAnimation<Color>(Color(0xFFD4AF37)),
              strokeWidth: 2,
            ),
          );
        },
        errorBuilder: (context, error, stackTrace) {
          // 加载失败时显示SVG或默认头像
          return _buildSvgOrDefaultAvatar();
        },
      );
    }

    // 最后显示SVG或默认头像
    return _buildSvgOrDefaultAvatar();
  }

  /// 构建SVG或默认头像
  Widget _buildSvgOrDefaultAvatar() {
    if (_avatarSvg != null) {
      // 使用 SizedBox + RepaintBoundary 包装确保固定尺寸并隔离渲染，避免布局问题
      return RepaintBoundary(
        child: SizedBox(
          width: 128,
          height: 128,
          child: SvgPicture.string(
            _avatarSvg!,
            width: 128,
            height: 128,
            fit: BoxFit.cover,
            placeholderBuilder: (context) => const Icon(
              Icons.person,
              size: 64,
              color: Color(0xFF8B5A2B),
            ),
          ),
        ),
      );
    }
    return const Icon(
      Icons.person,
      size: 64,
      color: Color(0xFF8B5A2B),
    );
  }

  /// 构建昵称输入区域
  Widget _buildNicknameSection() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标签
          const Text(
            '昵称',
            style: TextStyle(
              fontSize: 16,
              fontFamily: 'Inter',
              fontWeight: FontWeight.w500,
              height: 1.5,
              color: Color(0xFF5D4037),
            ),
          ),
          const SizedBox(height: 7),
          // 输入框
          Container(
            width: double.infinity,
            height: 54,
            decoration: BoxDecoration(
              color: const Color(0x80FFFFFF),
              borderRadius: BorderRadius.circular(12),
              border: Border.all(
                color: const Color(0x80FFFFFF),
                width: 1,
              ),
              boxShadow: const [
                BoxShadow(
                  color: Color(0x0D000000),
                  blurRadius: 2,
                  offset: Offset(0, 1),
                ),
              ],
            ),
            child: TextField(
              controller: _nicknameController,
              style: const TextStyle(
                fontSize: 16,
                fontFamily: 'Inter',
                height: 1.19,
                color: Color(0xFF5D4037),
              ),
              decoration: const InputDecoration(
                contentPadding: EdgeInsets.symmetric(horizontal: 16, vertical: 15),
                border: InputBorder.none,
                hintText: '请输入昵称',
                hintStyle: TextStyle(
                  fontSize: 16,
                  fontFamily: 'Inter',
                  height: 1.19,
                  color: Color(0x995D4037),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建保存按钮
  Widget _buildSaveButton() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: const BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [
            Color(0xFFFFE4B5),
            Color(0x00FFE4B5),
          ],
        ),
      ),
      child: GestureDetector(
        onTap: _isSaving ? null : _saveProfile,
        child: Container(
          width: double.infinity,
          height: 56,
          decoration: BoxDecoration(
            color: const Color(0xFFD4AF37),
            borderRadius: BorderRadius.circular(12),
            boxShadow: const [
              BoxShadow(
                color: Color(0x4DD4AF37),
                blurRadius: 14,
                offset: Offset(0, 4),
              ),
            ],
          ),
          child: Center(
            child: _isSaving
                ? const SizedBox(
                    width: 24,
                    height: 24,
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                      valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                    ),
                  )
                : const Text(
                    '保存',
                    style: TextStyle(
                      fontSize: 16,
                      fontFamily: 'Inter',
                      fontWeight: FontWeight.w700,
                      height: 1.5,
                      letterSpacing: 0.24,
                      color: Colors.white,
                    ),
                  ),
          ),
        ),
      ),
    );
  }

  /// 构建头像选择底部弹窗
  Widget _buildAvatarPickerSheet() {
    return Container(
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(16),
          topRight: Radius.circular(16),
        ),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 拖动指示条
          Container(
            width: 40,
            height: 4,
            margin: const EdgeInsets.only(top: 8),
            decoration: BoxDecoration(
              color: const Color(0x33000000),
              borderRadius: BorderRadius.circular(2),
            ),
          ),
          const SizedBox(height: 16),
          // 拍照选项
          _buildPickerOption(
            title: '拍照',
            onTap: _takePhoto,
            showDivider: true,
          ),
          // 从相册选择选项
          _buildPickerOption(
            title: '从相册选择',
            onTap: _pickFromGallery,
            showDivider: true,
          ),
          // 删除头像选项
          _buildPickerOption(
            title: '删除头像',
            onTap: _deleteAvatar,
            showDivider: false,
          ),
          const SizedBox(height: 8),
          // 取消按钮
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            child: GestureDetector(
              onTap: _cancelPicker,
              child: Container(
                width: double.infinity,
                height: 57,
                decoration: BoxDecoration(
                  color: const Color(0x33D4AF37),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: const Center(
                  child: Text(
                    '取消',
                    style: TextStyle(
                      fontSize: 16,
                      fontFamily: 'Inter',
                      fontWeight: FontWeight.w700,
                      height: 1.5,
                      color: Color(0xFF8B5A2B),
                    ),
                  ),
                ),
              ),
            ),
          ),
          const SizedBox(height: 16),
        ],
      ),
    );
  }

  /// 构建选择项
  Widget _buildPickerOption({
    required String title,
    required VoidCallback onTap,
    required bool showDivider,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16),
        child: Column(
          children: [
            Container(
              width: double.infinity,
              padding: const EdgeInsets.symmetric(vertical: 16),
              child: Text(
                title,
                style: const TextStyle(
                  fontSize: 16,
                  fontFamily: 'Inter',
                  height: 1.5,
                  color: Color(0xFF5D4037),
                ),
                textAlign: TextAlign.center,
              ),
            ),
            if (showDivider)
              Container(
                height: 1,
                color: const Color(0x1A000000),
              ),
          ],
        ),
      ),
    );
  }
}
