import 'package:flutter/material.dart';

import 'package:get/get.dart';
import 'package:naiyouwl/app/controller/controllers.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../../component/sys_app_bar.dart';
import '../controllers/login_controller.dart';

class LoginView extends GetView<LoginController> {
  const LoginView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Obx(() {
      if (controllers.global.errorMsg.value.isNotEmpty) {
        String message = controllers.global.errorMsg.value;
        controllers.global.errorMsg.value =
            ''; // Clear the error message immediately

        Future.delayed(Duration.zero, () async {
          bool? result = await controllers.dialog.showNormalDialog(
            title: "提示",
            content: message,
            cancelText: "取消",
            enterText: "确认",
          );
          if (result != null && result) {
            // User pressed "确认"
          } else {
            // User pressed "取消" or dismissed the dialog
          }
        });
      }
      return Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage("assets/images/login/login.png"),
            fit: BoxFit.fill,
          ),
        ),
        child: Scaffold(
            backgroundColor: Colors.transparent,
            appBar: SysAppBar(
              title: Text(controller.isReg.value ? "注册" : "登录"),
            ),
            body: LoginScreen(
              isLoading: controller.isLoading.value,
              username: controller.username(),
              password: controller.password(),
              isReg: controller.isReg.value,
              url: controller.sysConfig.value.userReset ?? "",
              onLogin: (username, password) {
                // 在这里处理登录逻辑，例如调用API
                controller.fetchLogin(username, password);
              },
              onRegin: (username, password) {
                controller.fetchRegLogin(username, password);
              },
              onLoginAndLogin: () {
                controller.isReg.value = controller.isReg.value == false;
              },
            )),
      );
    });
  }
}

class LoginScreen extends StatefulWidget {
  final Function(String username, String password) onLogin;
  final Function(String username, String password) onRegin;
  final void Function() onLoginAndLogin;
  final bool isLoading;
  final bool isReg;
  final String username;
  final String password;
  final String url;

  LoginScreen(
      {required this.isLoading,
      required this.onLogin,
      required this.onRegin,
      required this.onLoginAndLogin,
      required this.username,
      required this.password,
      required this.isReg,
      required this.url});

  @override
  _LoginScreenState createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  final _usernameController = TextEditingController();
  final _passwordController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 0),
      child: Center(
        child: Padding(
          padding: const EdgeInsets.fromLTRB(55, 70, 55, 0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              TextField(
                controller: _usernameController,
                decoration: const InputDecoration(
                  labelText: '邮箱',
                  hintText: '请输入邮箱',
                  border: InputBorder.none,
                ),
              ),
              const SizedBox(height: 16),
              TextField(
                controller: _passwordController,
                decoration: const InputDecoration(
                  labelText: '密码',
                  hintText: '输入密码',
                  border: InputBorder.none,
                ),
                obscureText: true,
              ),
              const SizedBox(height: 20),
              SizedBox(
                width: 200,
                height: 40,
                child: ElevatedButton(
                  onPressed: () {
                    if (!widget.isLoading) {
                      if (widget.isReg) {
                        final username = _usernameController.text;
                        final password = _passwordController.text;
                        widget.onRegin(username, password);
                      } else {
                        final username = _usernameController.text;
                        final password = _passwordController.text;
                        widget.onLogin(username, password);
                      }
                    }
                  },
                  child: widget.isLoading
                      ? const CircularProgressIndicator(
                          color: Colors.white,
                        )
                      : Text(widget.isReg ? '注册新用户' : '登录'),
                ),
              ),
              const SizedBox(height: 20),
              SizedBox(
                width: 200,
                height: 40,
                child: ElevatedButton(
                  onPressed: () {
                    widget.onLoginAndLogin();
                  },
                  child: Text(widget.isReg ? "切换登录" : "注册新用户"),
                ),
              ),
              const SizedBox(height: 20),
              Align(
                alignment: Alignment.centerRight,
                child: TextButton(
                    onPressed: () async {
                      await launchUrl(Uri.parse(widget.url));
                    },
                    child: const Text("忘记密码")),
              )
            ],
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    _usernameController.dispose();
    _passwordController.dispose();
    super.dispose();
  }
}
