import 'package:food_health/api/endpoints/user_api.dart';
import 'package:food_health/data/models/other_login_type.dart';
import 'package:food_health/router/config/route_paths.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:provider/provider.dart';
import 'package:remixicon/remixicon.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
import '../../../providers/app_store.dart';
import '../../../utils/common.dart';
import '../../../widgets/common/app_backend.dart';
import '../../../widgets/ui_kit/button/custom_button.dart';
import 'widget/agreement_box.dart';
import 'widget/widget.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  var _subLoading = false;

  ///协议
  bool _agree = false;

  ///谷歌登陆
  final GoogleSignIn _googleSignIn = GoogleSignIn.instance;

  ///邮箱输入框
  final TextEditingController _emailController = TextEditingController(text: "");
  final TextEditingController _passwordController = TextEditingController(text: "");

  //显示密码
  var _hidePassword = true;

  @override
  void initState() {
    super.initState();
    _ensureNetworkPermission();
    _initGoogleSign();
  }

  /// 预触发 iOS 网络权限弹窗
  Future<bool> _ensureNetworkPermission() async {
    try {
      await Dio().get(
        'https://captive.apple.com/hotspot-detect.html',
        options: Options(
          sendTimeout: const Duration(seconds: 3),
          receiveTimeout: const Duration(seconds: 3),
          headers: {'Cache-Control': 'no-cache'},
        ),
      );
      return true;
    } catch (_) {
      return false;
    }
  }

  void _initGoogleSign() {
    if (isAndroid()) {
      _googleSignIn.initialize(
        clientId: null,
        serverClientId: "512878764950-0bsl98c4q4p695mlmfn35qhmr2ld5n0o.apps.googleusercontent.com",
      );
    } else {
      _googleSignIn.initialize(
        clientId: "512878764950-1ke7slf0c6dlmchnuk0fqh3fe954gcf2.apps.googleusercontent.com",
        serverClientId: "512878764950-0bsl98c4q4p695mlmfn35qhmr2ld5n0o.apps.googleusercontent.com",
      );
    }

    _googleSignIn.authenticationEvents
        .listen((_) {
          print("登陆成功");
        })
        .onError((error) {
          print('登录错误: $error');
        });
  }

  ///谷歌登录
  void _handleGoogleSignIn() async {
    if (!_agree) {
      EasyLoading.showToast('Please read and agree to the terms first.');
      return;
    }

    try {
      // 如果用户未登录，则启动标准的 Google 登录
      if (_googleSignIn.supportsAuthenticate()) {
        // 使用 authenticate() 进行认证
        GoogleSignInAccount? user = await _googleSignIn.authenticate();
        var auth = user.authentication;

        // var res = await Dio().get("https://oauth2.googleapis.com/tokeninfo?id_token=${auth.idToken}");
        //登陆
        EasyLoading.show(status: "Logging in...");
        var res = await thirdLoginApi(auth.idToken!, OtherLoginType.google);
        EasyLoading.dismiss();
        _onLogin(res);
      }
      // } catch (e) {
      //   if (e is GoogleSignInException) {
      //     if (e.code == GoogleSignInExceptionCode.canceled) {
      //       // 用户取消登录
      //       print("User canceled login.");
      //     } else {
      //       // 其他错误
      //       print("Google Sign-In error: $e");
      //     }
      //   } else {
      //     print("Unknown error: $e");
      //   }
      // }
    } catch (e) {
      EasyLoading.showError("Login failed");
      print("登录错误: $e");
    }
  }

  ///apple登录
  void _handAppleSignIn() async {
    if (!_agree) {
      EasyLoading.showToast('Please read and agree to the terms first.');
      return;
    }

    try {
      final credential = await SignInWithApple.getAppleIDCredential(
        scopes: [
          AppleIDAuthorizationScopes.email,
          AppleIDAuthorizationScopes.fullName,
        ],
      );
      EasyLoading.show(status: "Logging in...");
      var res = await thirdLoginApi(credential.identityToken!, OtherLoginType.apple);
      EasyLoading.dismiss();
      _onLogin(res);
      print('Apple Credential: ${credential.identityToken}');
      print('Apple Email: ${credential.email}');
    } catch (e) {
      print('Error during Apple sign-in: $e');
    }
  }

  void _handSubmit() async {
    if (!_agree) {
      EasyLoading.showToast('Please read and agree to the terms first.');
      return;
    }
    if (_emailController.text.isEmpty) {
      //请输入邮箱
      EasyLoading.showError("Please enter your email");
      return;
    } else if (_passwordController.text.isEmpty) {
      EasyLoading.showError("Please enter your Password");
      return;
    }

    try {
      setState(() {
        _subLoading = true;
      });
      var isRegister = await checkRegisterApi(_emailController.text);
      if (!isRegister) {
        context.push(
          RoutePaths.loginCode,
          extra: {
            "email": _emailController.text,
            "password": _passwordController.text,
          },
        );
      } else {
        var res = await loginApi(_emailController.text, _passwordController.text);
        _onLogin(res);
      }
      setState(() {
        _subLoading = false;
      });
    } catch (e) {
      setState(() {
        _subLoading = false;
      });
    }
  }

  ///登陆的操作
  void _onLogin(dynamic res) {
    var appStore = context.read<AppStore>();
    appStore.setInfo(res);
    context.go(RoutePaths.layout);
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => FocusScope.of(context).unfocus(),
      child: AppBackend(
        child: Scaffold(
          resizeToAvoidBottomInset: false,
          body: SafeArea(
            child: Container(
              width: double.infinity,
              padding: EdgeInsets.only(
                top: 0.07.sh,
                left: 20,
                right: 20,
              ),
              child: ListView(
                children: [
                  LogoBox(),
                  PageHeader(),
                  InputBox(
                    hintText: "Email",
                    controller: _emailController,
                  ),
                  SizedBox(height: 15),
                  InputBox(
                    obscureText: _hidePassword,
                    hintText: "Password",
                    controller: _passwordController,
                    suffix: InkWell(
                      onTap: () {
                        setState(() {
                          _hidePassword = !_hidePassword;
                        });
                      },
                      child: Icon(
                        _hidePassword ? RemixIcons.eye_off_fill : RemixIcons.eye_fill,
                        size: 20,
                        color: Theme.of(context).colorScheme.onSurfaceVariant,
                      ),
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 20),
                    height: 45,
                    child: CustomButton(
                      loading: _subLoading,
                      round: false,
                      onPressed: _handSubmit,
                      child: Text("Continue"),
                    ),
                  ),
                  LoginDivider(),
                  OtherButton(
                    title: "Continue with Google",
                    icon: "assets/image/google.png",
                    onTap: () {
                      _handleGoogleSignIn();
                    },
                  ),
                  SizedBox(height: 15),
                  OtherButton(
                    title: "Continue with Apple",
                    icon: "assets/image/apple.png",
                    onTap: () {
                      _handAppleSignIn();
                    },
                  ),
                  Container(
                    width: double.infinity,
                    margin: EdgeInsets.only(top: 40),
                    alignment: Alignment.center,
                    child: AgreementBox(
                      checked: _agree,
                      onChanged: (value) {
                        setState(() {
                          _agree = value;
                        });
                      },
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
