// login_screen.dart
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../base/base_screen.dart';
import '../../base/basic_state.dart';
import '../../permission/biometric_manager.dart';
import '../../resouce/base_color.dart';
import '../../widgets/alert/custom_alert_dialog.dart';
import '../../widgets/alert/data_alert_model.dart';
import '../../widgets/back_button.dart';
import '../../widgets/support_button.dart';
import 'login_viewmodel.dart';

class LoginScreen extends BaseScreen {
  final String phoneNumber;
  final String? fullName;
  const LoginScreen({super.key, required this.phoneNumber, this.fullName});

  @override
  State<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends BaseState<LoginScreen> with BasicState {
  final TextEditingController _phoneController = TextEditingController();
  final FocusNode _focusNode = FocusNode();
  final loginVM = Get.put(LoginViewModel());

  @override
  void initState() {
    super.initState();
    loginVM.onShowChangePass = (message) {
      Get.dialog(
        CustomAlertDialog(
          alertData: DataAlertModel(
            background: "assets/images/bg_alert_header.png",
            title: "Cài đặt mật khẩu",
            content: message,
            buttons: [
              AlertButton(
                text: "Cài đặt ngay",
                onPressed: () {

                },
                bgColor: BaseColor.primary500,
                textColor: Colors.white,
                isPrimary: true,
              ),
            ],
          ),
        ),
      );
    };

    loginVM.onShowDeviceError = (message) {
      loginVM.onChangePhonePressed();
    };

    loginVM.onShowInvalidAccount = (message) {
      Get.dialog(
        CustomAlertDialog(
          alertData: DataAlertModel(
            background: "assets/images/bg_alert_header.png",
            title: "",
            content: message,
            buttons: [
              AlertButton(
                text: "Quên mật khẩu",
                onPressed: () {
                  loginVM.onForgotPassPressed(widget.phoneNumber);
                },
                bgColor: BaseColor.primary500,
                textColor: Colors.white,
                isPrimary: true,
              ),
              AlertButton(
                text: "Đã hiểu",
                onPressed: () {
                  Get.back();
                },
                bgColor: Colors.white,
                textColor: Colors.black,
                isPrimary: true,
              ),
            ],
          ),
        ),
      );
    };

    loginVM.onShowAlertError = (message) {
      if (message.isNotEmpty) {
        showAlertError(message);
      }
    };

    WidgetsBinding.instance.addPostFrameCallback((_) {
      _focusNode.requestFocus();
    });
  }

  @override
  void dispose() {
    _focusNode.dispose();
    _phoneController.dispose();
    super.dispose();
  }

  @override
  Widget createBody() {
    // final loginVM = Get.find<LoginViewModel>();
    return GestureDetector(
      onTap: hideKeyboard,
      child: Scaffold(
        resizeToAvoidBottomInset: false,
        appBar: AppBar(
          automaticallyImplyLeading: false,
          backgroundColor: Colors.white,
          centerTitle: true,
          leading: CustomBackButton(),
          actions: [SupportButton()],
        ),
        backgroundColor: Colors.white,
        body: SafeArea(
          child: Stack(
            children: [
              SingleChildScrollView(
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    Text(
                      "Đăng nhập",
                      style: TextStyle(color: BaseColor.second600, fontSize: 24, fontWeight: FontWeight.bold),
                    ),
                    const SizedBox(height: 16),
                    _buildWelcomeText(loginVM),
                    const SizedBox(height: 16),
                    _buildPasswordField(loginVM),
                    _buildErrorText(loginVM),
                    const SizedBox(height: 8),
                    _buildActionRow(loginVM),
                    const SizedBox(height: 8),
                    _buildBiometricSection(loginVM),
                  ],
                ),
              ),
              SizedBox.expand(),
              Positioned(left: 0, right: 0, bottom: 16, child: _buildLoginButton(loginVM)),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildWelcomeText(LoginViewModel vm) {
    return RichText(
      text: TextSpan(
        style: const TextStyle(fontSize: 14, color: BaseColor.second500),
        children: [
          const TextSpan(text: "Xin chào "),
          TextSpan(text: widget.fullName ?? "Quý Khách "),
          TextSpan(
            text: widget.phoneNumber,
            style: const TextStyle(fontWeight: FontWeight.w500, color: BaseColor.primary500),
          ),
        ],
      ),
    );
  }

  Widget _buildPasswordField(LoginViewModel vm) {
    return Obx(() {
      return TextField(
        controller: _phoneController,
        focusNode: _focusNode,
        keyboardType: TextInputType.number,
        obscureText: !vm.isPasswordVisible.value,
        onChanged: vm.onPasswordChanged,
        decoration: InputDecoration(
          hintText: "Nhập mật khẩu",
          prefixIcon: const Icon(Icons.password, color: BaseColor.second500),
          hintStyle: const TextStyle(color: BaseColor.second200),
          fillColor: Colors.white,
          filled: true,
          contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 14),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(8),
            borderSide: const BorderSide(color: Colors.grey, width: 1),
          ),
          enabledBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(8),
            borderSide: const BorderSide(color: Colors.grey, width: 1),
          ),
          focusedBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(8),
            borderSide: const BorderSide(color: Colors.grey, width: 1),
          ),
          suffixIcon: IconButton(
            icon: Icon(
              vm.isPasswordVisible.value ? Icons.visibility : Icons.visibility_off,
              color: BaseColor.second500,
            ),
            onPressed: vm.togglePasswordVisibility,
          ),
        ),
      );
    });
  }

  Widget _buildErrorText(LoginViewModel vm) {
    return Obx(() {
      if (vm.loginState.value == LoginState.error) {
        return Padding(
          padding: const EdgeInsets.only(top: 4),
          child: Text("Sai mật khẩu, vui lòng thử lại!", style: TextStyle(color: BaseColor.primary400)),
        );
      }
      return const SizedBox.shrink();
    });
  }

  Widget _buildActionRow(LoginViewModel vm) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        TextButton(
          onPressed: vm.onChangePhonePressed,
          child: const Text("Đổi số điện thoại", style: TextStyle(fontSize: 14, color: Color(0xFF3662FE))),
        ),
        TextButton(
          onPressed: () {
            vm.onForgotPassPressed(widget.phoneNumber);
          },
          child: const Text("Quên mật khẩu?", style: TextStyle(fontSize: 14, color: Color(0xFF3662FE))),
        ),
      ],
    );
  }

  Widget _buildBiometricSection(LoginViewModel vm) {
    return Obx(() {
      // Nếu thiết bị không hỗ trợ => ẩn
      // if (vm.biometricType.value == BiometricTypeEnum.none) {
      //   return const SizedBox.shrink();
      // }
      // Hiển thị 1 icon tuỳ loại
      IconData icon = Icons.fingerprint;
      String label = "Vân tay";
      if (vm.biometricType.value == BiometricTypeEnum.faceId) {
        icon = Icons.face;
        label = "Face ID";
      }
      return Column(
        children: [
          IconButton(
              icon: Icon(icon, size: 36),
              onPressed: () => vm.onBiometricLoginPressed(widget.phoneNumber),
          ),
          Text("Đăng nhập bằng $label"),
        ],
      );
    });
  }

  Widget _buildLoginButton(LoginViewModel vm) {
    return Obx(() {
      bool enabled = false;
      Color color = BaseColor.second400;
      switch (vm.loginState.value) {
        case LoginState.typing:
          if (vm.password.value.isNotEmpty) {
            color = BaseColor.primary500;
            enabled = true;
          } else {
            enabled = false;
            color = BaseColor.second400;
          }
          break;
        case LoginState.done:
          color = BaseColor.primary500;
          enabled = true;
          break;
        case LoginState.error:
        case LoginState.idle:
          color = BaseColor.second400;
          break;
      }

      return Container(
        color: Colors.white,
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        child: ElevatedButton(
          style: ElevatedButton.styleFrom(
            backgroundColor: color,
            minimumSize: const Size.fromHeight(48),
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
          ),
          onPressed: () {
            enabled ? vm.onLoginPressed(widget.phoneNumber) : null;
          },
          child: const Text(
            "Đăng nhập",
            style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: Colors.white),
          ),
        ),
      );
    });
  }
}
