import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import '../../../../core/di/injection_container.dart';
import '../../../../core/services/multi_account_service.dart';
import '../../../../routes/route_paths.dart';
import '../providers/auth_provider.dart';

/// 手机号+密码登录页面
/// 用于"登录账号"功能
class PhoneLoginPage extends ConsumerStatefulWidget {
  const PhoneLoginPage({super.key});

  @override
  ConsumerState<PhoneLoginPage> createState() => _PhoneLoginPageState();
}

class _PhoneLoginPageState extends ConsumerState<PhoneLoginPage> {
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final FocusNode _phoneFocusNode = FocusNode();
  final FocusNode _passwordFocusNode = FocusNode();

  bool _isLoggingIn = false;
  String? _errorMessage;
  bool _obscurePassword = true; // 是否隐藏密码

  @override
  void dispose() {
    _phoneController.dispose();
    _passwordController.dispose();
    _phoneFocusNode.dispose();
    _passwordFocusNode.dispose();
    super.dispose();
  }

  /// 验证手机号格式
  bool _isValidPhoneNumber(String phone) {
    // 中国大陆手机号：1开头，第二位3-9，共11位
    final regex = RegExp(r'^1[3-9]\d{9}$');
    return regex.hasMatch(phone);
  }

  /// 验证输入
  String? _validateInputs() {
    final phone = _phoneController.text.trim();
    final password = _passwordController.text;

    if (phone.isEmpty) {
      return '请输入手机号';
    }

    if (!_isValidPhoneNumber(phone)) {
      return '请输入正确的手机号';
    }

    if (password.isEmpty) {
      return '请输入密码';
    }

    if (password.length < 6) {
      return '密码至少6位';
    }

    return null;
  }

  /// 执行登录
  Future<void> _login() async {
    // 验证输入
    final validationError = _validateInputs();
    if (validationError != null) {
      setState(() {
        _errorMessage = validationError;
      });
      return;
    }

    setState(() {
      _isLoggingIn = true;
      _errorMessage = null;
    });

    try {
      final phone = _phoneController.text.trim();
      final password = _passwordController.text;

      debugPrint('[PhoneLoginPage] 开始登录 - 手机号: $phone');

      // 获取 AccountService
      final accountService = ref.read(accountServiceProvider);

      // 获取设备ID
      final deviceId = await accountService.getDeviceId();
      debugPrint('[PhoneLoginPage] 获取设备ID成功');

      // 调用登录 API
      final response = await accountService.loginWithPassword(
        phoneNumber: phone,
        password: password,
        deviceId: deviceId,
      );

      debugPrint('[PhoneLoginPage] 登录成功 - accountSequence: ${response.accountSequence}');

      if (!mounted) return;

      // 获取用户资料并添加到多账号列表
      try {
        final profile = await accountService.getMyProfile();
        final multiAccountService = ref.read(multiAccountServiceProvider);

        await multiAccountService.addAccount(
          AccountSummary(
            userSerialNum: response.accountSequence,
            username: profile['nickname'] as String? ?? '用户${response.accountSequence}',
            avatarSvg: profile['avatarSvg'] as String?,
            avatarUrl: profile['avatarUrl'] as String?,
            createdAt: DateTime.now(),
          ),
        );
        await multiAccountService.setCurrentAccountId(response.accountSequence);
        debugPrint('[PhoneLoginPage] 已添加到多账号列表');
      } catch (e) {
        debugPrint('[PhoneLoginPage] 获取用户资料失败，使用默认信息: $e');
        // 即使获取资料失败，也添加到账号列表（使用默认信息）
        final multiAccountService = ref.read(multiAccountServiceProvider);
        await multiAccountService.addAccount(
          AccountSummary(
            userSerialNum: response.accountSequence,
            username: '用户${response.accountSequence}',
            createdAt: DateTime.now(),
          ),
        );
        await multiAccountService.setCurrentAccountId(response.accountSequence);
      }

      if (mounted) {
        // 更新认证状态
        await ref.read(authProvider.notifier).checkAuthStatus();

        // 跳转到主页（龙虎榜）
        context.go(RoutePaths.ranking);
      }
    } catch (e) {
      debugPrint('[PhoneLoginPage] 登录失败: $e');
      setState(() {
        _errorMessage = '登录失败: $e';
      });
    } finally {
      if (mounted) {
        setState(() {
          _isLoggingIn = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Color(0xFFFFF5E6), // 浅米色
              Color(0xFFEAE0C8), // 浅橙色
            ],
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              // 顶部导航栏
              _buildAppBar(),
              // 内容区域
              Expanded(
                child: GestureDetector(
                  onTap: () => FocusScope.of(context).unfocus(),
                  child: SingleChildScrollView(
                    padding: EdgeInsets.symmetric(horizontal: 24.w),
                    child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(height: 32.h),
                // 手机号输入框
                _buildPhoneInput(),
                SizedBox(height: 16.h),
                // 密码输入框
                _buildPasswordInput(),
                SizedBox(height: 12.h),
                // 找回密码
                _buildForgotPassword(),
                // 错误提示
                if (_errorMessage != null) ...[
                  SizedBox(height: 16.h),
                  _buildErrorMessage(),
                ],
                SizedBox(height: 24.h),
                // 登录按钮
                _buildLoginButton(),
                SizedBox(height: 24.h),
                // 分割线和提示
                _buildDivider(),
                SizedBox(height: 24.h),
                // 注册提示
                _buildRegisterHint(),
                      SizedBox(height: 32.h),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    ),
    );
  }

  /// 构建顶部导航栏
  Widget _buildAppBar() {
    return Container(
      height: 56.h,
      padding: EdgeInsets.symmetric(horizontal: 8.w),
      child: Row(
        children: [
          IconButton(
            icon: const Icon(Icons.arrow_back_ios, color: Color(0xFF5D4037)),
            onPressed: () => context.pop(),
          ),
          Expanded(
            child: Text(
              '登录账号',
              style: TextStyle(
                fontSize: 18.sp,
                fontWeight: FontWeight.w600,
                color: const Color(0xFF5D4037),
              ),
              textAlign: TextAlign.center,
            ),
          ),
          SizedBox(width: 48.w), // 平衡左侧返回按钮的宽度
        ],
      ),
    );
  }

  /// 构建手机号输入框
  Widget _buildPhoneInput() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '手机号',
          style: TextStyle(
            fontSize: 14.sp,
            color: const Color(0xFF5D4037),
            fontWeight: FontWeight.w600,
          ),
        ),
        SizedBox(height: 8.h),
        Container(
          padding: EdgeInsets.symmetric(vertical: 12.h, horizontal: 0),
          decoration: BoxDecoration(
            border: Border(
              bottom: BorderSide(
                color: const Color(0xFFD4A574),
                width: 1,
              ),
            ),
          ),
          child: TextField(
            controller: _phoneController,
            focusNode: _phoneFocusNode,
            keyboardType: TextInputType.phone,
            inputFormatters: [
              FilteringTextInputFormatter.digitsOnly,
              LengthLimitingTextInputFormatter(11),
            ],
            style: TextStyle(
              fontSize: 16.sp,
              color: const Color(0xFF5D4037),
              fontWeight: FontWeight.w500,
            ),
            decoration: InputDecoration(
              hintText: '请输入手机号',
              hintStyle: TextStyle(
                fontSize: 16.sp,
                color: const Color(0xFFB8956A),
              ),
              border: InputBorder.none,
              isDense: false,
              contentPadding: EdgeInsets.zero,
            ),
            onChanged: (_) {
              if (_errorMessage != null) {
                setState(() => _errorMessage = null);
              }
            },
          ),
        ),
      ],
    );
  }

  /// 构建密码输入框
  Widget _buildPasswordInput() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '密码',
          style: TextStyle(
            fontSize: 14.sp,
            color: const Color(0xFF5D4037),
            fontWeight: FontWeight.w600,
          ),
        ),
        SizedBox(height: 8.h),
        Container(
          padding: EdgeInsets.symmetric(vertical: 12.h, horizontal: 0),
          decoration: BoxDecoration(
            border: Border(
              bottom: BorderSide(
                color: const Color(0xFFD4A574),
                width: 1,
              ),
            ),
          ),
          child: Row(
            children: [
              Expanded(
                child: TextField(
                  controller: _passwordController,
                  focusNode: _passwordFocusNode,
                  obscureText: _obscurePassword,
                  style: TextStyle(
                    fontSize: 16.sp,
                    color: const Color(0xFF5D4037),
                    fontWeight: FontWeight.w500,
                  ),
                  decoration: InputDecoration(
                    hintText: '请输入密码',
                    hintStyle: TextStyle(
                      fontSize: 16.sp,
                      color: const Color(0xFFB8956A),
                    ),
                    border: InputBorder.none,
                    isDense: false,
                    contentPadding: EdgeInsets.zero,
                  ),
                  onChanged: (_) {
                    if (_errorMessage != null) {
                      setState(() => _errorMessage = null);
                    }
                  },
                  onSubmitted: (_) => _login(),
                ),
              ),
              // 密码可见性切换按钮
              GestureDetector(
                onTap: () {
                  setState(() {
                    _obscurePassword = !_obscurePassword;
                  });
                },
                child: Icon(
                  _obscurePassword ? Icons.visibility_off : Icons.visibility,
                  color: const Color(0xFF8B6F47),
                  size: 20.sp,
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  /// 构建找回密码链接
  Widget _buildForgotPassword() {
    return Align(
      alignment: Alignment.centerRight,
      child: GestureDetector(
        onTap: () {
          debugPrint('[PhoneLoginPage] 跳转到找回密码页面');
          context.push(RoutePaths.forgotPassword);
        },
        child: Text(
          '找回密码',
          style: TextStyle(
            fontSize: 14.sp,
            color: const Color(0xFF8B5A2B),
            fontWeight: FontWeight.w500,
          ),
        ),
      ),
    );
  }

  /// 构建错误提示
  Widget _buildErrorMessage() {
    return Container(
      padding: EdgeInsets.all(12.w),
      decoration: BoxDecoration(
        color: Colors.red.withOpacity(0.1),
        borderRadius: BorderRadius.circular(8.r),
        border: Border.all(
          color: Colors.red.withOpacity(0.3),
          width: 1,
        ),
      ),
      child: Row(
        children: [
          Icon(
            Icons.error_outline,
            color: Colors.red,
            size: 16.sp,
          ),
          SizedBox(width: 8.w),
          Expanded(
            child: Text(
              _errorMessage!,
              style: TextStyle(
                fontSize: 14.sp,
                color: Colors.red,
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建登录按钮
  Widget _buildLoginButton() {
    final canLogin = !_isLoggingIn &&
        _phoneController.text.trim().isNotEmpty &&
        _passwordController.text.isNotEmpty;

    return SizedBox(
      width: double.infinity,
      height: 50.h,
      child: ElevatedButton(
        onPressed: canLogin ? _login : null,
        style: ElevatedButton.styleFrom(
          backgroundColor: canLogin
              ? const Color(0xFF8B5A2B)
              : const Color(0xFFD4C4B0),
          disabledBackgroundColor: const Color(0xFFD4C4B0),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12.r),
          ),
          elevation: 0,
        ),
        child: _isLoggingIn
            ? SizedBox(
                width: 20.w,
                height: 20.h,
                child: const CircularProgressIndicator(
                  strokeWidth: 2,
                  valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                ),
              )
            : Text(
                '登录',
                style: TextStyle(
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w700,
                  color: canLogin ? Colors.white : const Color(0xFFB8956A),
                ),
              ),
      ),
    );
  }

  /// 构建分割线
  Widget _buildDivider() {
    return Row(
      children: [
        Expanded(
          child: Divider(
            color: const Color(0xFFD4A574),
            thickness: 1,
          ),
        ),
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          child: Text(
            '或',
            style: TextStyle(
              fontSize: 14.sp,
              color: const Color(0xFF8B6F47),
              fontWeight: FontWeight.w500,
            ),
          ),
        ),
        Expanded(
          child: Divider(
            color: const Color(0xFFD4A574),
            thickness: 1,
          ),
        ),
      ],
    );
  }

  /// 构建注册提示
  Widget _buildRegisterHint() {
    return Center(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(
            '还没有账号？',
            style: TextStyle(
              fontSize: 14.sp,
              color: const Color(0xFF8B6F47),
              fontWeight: FontWeight.w500,
            ),
          ),
          SizedBox(width: 4.w),
          GestureDetector(
            onTap: () {
              // 返回向导页
              context.go(RoutePaths.guide);
            },
            child: Text(
              '立即注册',
              style: TextStyle(
                fontSize: 14.sp,
                color: const Color(0xFF8B5A2B),
                fontWeight: FontWeight.w700,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
