import 'dart:async';

import 'package:app/providers/user_store.dart';
import 'package:app/request/api/user_api.dart';
import 'package:app/router/route_paths.dart';
import 'package:app/widgets/base/button/index.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:provider/provider.dart';
import 'package:remixicon/remixicon.dart';

import 'widgets/login_input.dart';

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

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

class _LoginPageState extends State<LoginPage> {
  ///协议
  bool _agree = false;

  ///输入框
  final TextEditingController _telController = TextEditingController(text: "");
  final TextEditingController _codeController = TextEditingController(text: "");

  ///登录中
  bool _loading = false;

  ///验证码倒计时
  var _countDown = 0;
  Timer? _timer;

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

  ///点击发送验证码
  void _sendCode() async {
    RegExp regExp = RegExp(r'^1\d{10}$');
    if (!regExp.hasMatch(_telController.text)) {
      EasyLoading.showToast("请填写正确的手机号");
      return;
    }
    sendCodeApi(_telController.text);
    setState(() {
      _countDown = 60;
    });
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      setState(() {
        _countDown--;
      });
      if (_countDown <= 0) {
        _timer?.cancel();
        _timer = null;
      }
    });
  }

  ///提交登录
  void _handSubmit() async {
    RegExp regExp = RegExp(r'^1\d{10}$');
    if (!regExp.hasMatch(_telController.text) || _codeController.text.isEmpty) {
      EasyLoading.showToast("请填写完整手机号或验证码");
      return;
    }
    try {
      setState(() {
        _loading = true;
      });
      var loginRes = await loginApi(_telController.text, _codeController.text);
      if (mounted) {
        UserStore userStore = context.read<UserStore>();

        //设置登录信息l
        await userStore.setToken(loginRes.accessToken);
        await userStore.setUserInfo();

        if (!mounted) return;
        if (userStore.userInfo?.accountType == 1) {
          context.go(RoutePaths.sHome);
        } else if(userStore.userInfo?.accountType == 2){
          context.go(RoutePaths.tHome);
        }else{
          EasyLoading.showError("账号类型错误");

        }
      }
    } finally {
      setState(() {
        _loading = false;
      });
    }
  }

  @override
  void dispose() {
    super.dispose();
    _timer?.cancel();
    _timer = null;
  }

  @override
  Widget build(BuildContext context) {
    //是否已发送验证码
    bool codeOk = _countDown == 0;
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: SafeArea(
        child: Container(
          padding: EdgeInsets.only(left: 20, right: 20, top: 0.08.sh, bottom: 40),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                margin: EdgeInsets.only(bottom: 40),
                child: Text("登陆学光自习室", style: Theme.of(context).textTheme.titleLarge),
              ),
              LoginInput(
                hintText: "请输入手机号",
                controller: _telController,
                suffix: Visibility(
                  visible: _telController.text.isNotEmpty,
                  child: InkWell(
                    onTap: () {
                      _telController.clear();
                    },
                    child: Icon(RemixIcons.close_circle_fill, size: 20),
                  ),
                ),
              ),
              Container(
                margin: EdgeInsets.only(top: 20),
                child: Row(
                  spacing: 20,
                  children: [
                    Expanded(
                      child: LoginInput(
                        hintText: "输入验证码",
                        controller: _codeController,
                        maxLength: 4,
                      ),
                    ),
                    SizedBox(
                      height: 45,
                      child: Button(
                        text: codeOk ? "发送验证码" : "$_countDown 秒后发送",
                        radius: BorderRadius.circular(10),
                        disabled: !codeOk,
                        onPressed: _sendCode,
                      ),
                    ),
                  ],
                ),
              ),

              Container(
                margin: EdgeInsets.only(top: 40),
                height: 50,
                child: Button(
                  text: "登 录",
                  loading: _loading,
                  onPressed: _handSubmit,
                ),
              ),
              // Container(
              //   width: double.infinity,
              //   margin: EdgeInsets.only(top: 20),
              //   alignment: Alignment.center,
              //   child: LoginAgree(
              //     value: _agree,
              //     onChanged: (value) {
              //       setState(() {
              //         _agree = value!;
              //       });
              //     },
              //   ),
              // ),
            ],
          ),
        ),
      ),
    );
  }
}
