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 '../../resources/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 {
  const LoginScreen({super.key});

  @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());
  bool _autoSubmitted = false; // prevent duplicate submits when reaching 6 chars

  late final String phoneNumber;
  late String fullName = "";

  @override
  void initState() {
    super.initState();
    final args = Get.arguments;
    if (args is Map) {
      phoneNumber = args['phone'];
      fullName = args['fullName'] ?? 'Quý khách';
    }
    loginVM.onShowChangePass = (message) {
      Get.dialog(
        CustomAlertDialog(
          alertData: DataAlertModel(
            localHeaderImage: "assets/images/bg_alert_header.png",
            title: "Cài đặt mật khẩu",
            description: message,
            buttons: [
              AlertButton(
                text: "Cài đặt ngay",
                onPressed: () {
                  loginVM.onForgotPassPressed(phoneNumber);
                },
                bgColor: BaseColor.primary500,
                textColor: Colors.white,
              ),
            ],
          ),
        ),
      );
    };

    loginVM.onShowDeviceError = (message) {
      showAlertError(content: message, onConfirmed: () {
        loginVM.onChangePhonePressed();
      });
    };

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

    loginVM.onShowAlertError = (message) {
      if (message.isNotEmpty) {
        showAlertError(content: 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: fullName.isEmpty ? "Quý Khách " : "$fullName "),
          TextSpan(
            text: 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: (value) {
          vm.onPasswordChanged(value);
          // Auto submit when password reaches 6 characters
          if (!_autoSubmitted && value.length == 6) {
            hideKeyboard();
            _autoSubmitted = true;
            vm.onLoginPressed(phoneNumber);
          }
          // Reset guard when user deletes characters
          if (value.length < 6 && _autoSubmitted) {
            _autoSubmitted = false;
          }
        },
        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(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.isSupportedBiometric.value) {
        return const SizedBox.shrink();
      }
      String icon = 'assets/images/ic_fingerprint.png';
      String label = "vân tay";
      if (vm.biometricType.value == BiometricTypeEnum.faceId) {
        icon = 'assets/images/ic_face.png';
        label = "Face ID";
      }
      return Column(
        children: [
          IconButton(
              icon: Image.asset(icon, width: 40, height: 40),
              onPressed: () => vm.onBiometricLoginPressed(phoneNumber),
          ),
          Text("Đăng nhập bằng $label"),
        ],
      );
    });
  }

  Widget _buildLoginButton(LoginViewModel vm) {
    return Obx(() {
      bool enabled = false;
      Color color = BaseColor.second400;
      if (vm.loginState.value == LoginState.typing && vm.password.value.length >= 6) {
        color = BaseColor.primary500;
        enabled = true;
      }
      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: () {
            hideKeyboard();
            enabled ? vm.onLoginPressed(phoneNumber) : null;
          },
          child: const Text(
            "Đăng nhập",
            style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: Colors.white),
          ),
        ),
      );
    });
  }
}
