import 'dart:developer';
import 'dart:io';
import 'package:elysia/page/HomePage.dart';
import 'package:elysia/page/RegistrationPage.dart';
import 'package:elysia/plugin/HTTP.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:typed_data';
import 'package:oktoast/oktoast.dart';
import '../plugin/C.dart';

import 'package:path_provider/path_provider.dart';

import '../plugin/HiverCache.dart';
import '../plugin/LoadingOverlay.dart';
import '../plugin/RouteAnimation.dart';
import '../plugin/WebSocketService.dart';
import 'ForgetPasswordPage.dart';
void main() {
  runApp(MaterialApp(
    debugShowCheckedModeBanner: false,
    home: LoginPage(),
    theme: ThemeData(
      primarySwatch: Colors.blue,
    ),
  ));
}

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();


}

class _LoginPageState extends State<LoginPage> {
  final TextEditingController _usernameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final TextEditingController _captchaController = TextEditingController();

  Uint8List? _captchaImageBytes;
  String? _captchaUUID;
  bool _loadingCaptcha = false;

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

  Future<void> _fetchCaptcha() async {
    setState(() {
      _loadingCaptcha = true;
    });
    final url = Uri.parse('${C.BASE_URL}/authorization/captcha');
    try {
      final response = await http.get(url);
      if (response.statusCode == 200) {
        setState(() {
          _captchaImageBytes = response.bodyBytes;
          _captchaUUID = response.headers['captcha-uuid'];
          _loadingCaptcha = false;
          log(response.headers['captcha-uuid'] ?? '');
        });
      } else {
        setState(() {
          _loadingCaptcha = false;
        });
        print("获取验证码失败: ${response.statusCode}");
      }
    } catch (e) {
      setState(() {
        _loadingCaptcha = false;
      });
      print("获取验证码异常: $e");
    }
  }

  Future<void> _login() async {
    String username = _usernameController.text;
    String password = _passwordController.text;
    String captcha = _captchaController.text;
    LoadingOverlay.show(
      context: context,
      barrierColor: Colors.black54,
    );
    try{
      Map<String,String> header = {"captcha":captcha,"captcha-code":_captchaUUID!};
      dynamic result = await HTTP.create('${C.BASE_URL}/authorization/login').setHeader(header).setContentType(ContentType.json).setRequestType(RequestType.POST).setBody({"user":username,"password":password}).execute();

      if(result['code']!=200){
        LoadingOverlay.hide();
        showToast(result["message"],position: ToastPosition.bottom);
        _fetchCaptcha();
        return;
      }
      C.TOKEN={"Authorization":result['data']};
      dynamic profileResult = await HTTP
          .create('${C.BASE_URL}/authorization/profile')
          .setHeader( C.TOKEN)
          .setContentType(ContentType.json)
          .setRequestType(RequestType.POST)
          .execute();
      if (profileResult['code'] == 200) {
        C.PROFILE = profileResult['data'];
      }
      final appDocDir = await getApplicationDocumentsDirectory();
      final configDir = Directory('${appDocDir.path}/config');
      final file = File('${configDir.path}/auth.token');
      await file.writeAsString(C.TOKEN["Authorization"]!);
      C.socket = WebSocketService();
      C.socket.init();
      await C.socket.connect( "${C.BASE_WS_URL}/socket/chat?authorization=${C.TOKEN["Authorization"].toString().replaceAll(" ", "%20")}");
      LoadingOverlay.hide();
      HiverCache.init(profileResult["data"]["userName"]);
      Navigator.pushReplacement(context,RouteAnimation(HomePage(),Offset(1,0)));
    }catch(e){
      log(e.toString());
      LoadingOverlay.hide();
    }
  }

  @override
  Widget build(BuildContext context) {

    final theme = Theme.of(context);
    final activeColor = theme.colorScheme.primary;
    return Scaffold(
      backgroundColor: Colors.blue.shade50,
      // 避免键盘挤压内容
      resizeToAvoidBottomInset: false,
      body: Center(
        child: SingleChildScrollView(
          padding: EdgeInsets.symmetric(horizontal: 24),
          child: Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(16),
              color: Colors.white, // 替代卡片阴影
            ),
            padding: EdgeInsets.all(24),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text("Elysia",style: TextStyle(fontWeight: FontWeight.bold,fontSize: 40,color: activeColor),),
                SizedBox(height: 32),
                // 账号
                TextField(
                  controller: _usernameController,
                  decoration: InputDecoration(
                    labelText: "账号/邮箱",
                    prefixIcon: Icon(Icons.person),
                    border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
                    filled: true,
                    fillColor: Colors.blue.shade50,
                  ),
                ),
                SizedBox(height: 16),

                // 密码
                TextField(
                  controller: _passwordController,
                  obscureText: true,
                  decoration: InputDecoration(
                    labelText: "密码",
                    prefixIcon: Icon(Icons.lock),
                    border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
                    filled: true,
                    fillColor: Colors.blue.shade50,
                  ),
                ),
                SizedBox(height: 16),

                // 验证码
                Row(
                  children: [
                    Expanded(
                      child: TextField(
                        controller: _captchaController,
                        decoration: InputDecoration(
                          labelText: "验证码",
                          prefixIcon: Icon(Icons.verified),
                          border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
                          filled: true,
                          fillColor: Colors.blue.shade50,
                        ),
                      ),
                    ),
                    SizedBox(width: 8),
                    Container(decoration: BoxDecoration(border: BoxBorder.all(color: Colors.grey.shade200),borderRadius: BorderRadius.circular(12)),height: 55, child: Padding(padding: EdgeInsets.symmetric(horizontal: 5),child: GestureDetector(
                      onTap: _fetchCaptcha,
                      child: Container(
                        width: 90,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(8),
                          color: Colors.transparent,
                        ),
                        child: _loadingCaptcha
                            ? Center(child: CircularProgressIndicator(strokeWidth: 2))
                            : _captchaImageBytes != null
                            ? ClipRRect(
                          borderRadius: BorderRadius.circular(8),
                          child: FittedBox(
                            fit: BoxFit.contain,
                            child: Image.memory(_captchaImageBytes!),
                          ),
                        )
                            : Center(child: Icon(Icons.image_not_supported)),
                      ),
                    ),),),
                  ],
                ),
                SizedBox(height: 24),

                // 登录按钮
                SizedBox(
                  width: double.infinity,
                  height: 48,
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(24)),
                      padding: EdgeInsets.symmetric(vertical: 12),
                      backgroundColor: activeColor,
                      textStyle: TextStyle(fontSize: 18),
                    ),
                    onPressed: _login,
                    child: Text("登录"),
                  ),
                ),
                SizedBox(height: 16),

                // 底部注册 & 忘记密码，不可点击
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    GestureDetector(onTap: () {
                      Navigator.push(context, RouteAnimation(RegistrationPage(), Offset(-1,0)));
                    },child: Text(
                      "注册",
                      style: TextStyle(color: activeColor),
                    ),),
                    GestureDetector(onTap: (){
                      Navigator.push(context, RouteAnimation(ForgetPasswordPage(), Offset(1,0)));
                    },child: Text(
                      "忘记密码?",
                      style: TextStyle(color: activeColor),
                    ),),
                  ],
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
