// login_screen.dart
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 'login_view_model.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();

  @override
  Widget createBody() {
    // Khởi tạo hoặc lấy LoginViewModel
    final loginVM = Get.put(LoginViewModel());
    return GestureDetector(
      onTap: hideKeyboard,
      child: Scaffold(
        // Để nội dung nâng lên khi bàn phím xuất hiện
        resizeToAvoidBottomInset: false,
        appBar: AppBar(
          automaticallyImplyLeading: false,
          backgroundColor: Colors.white,
          centerTitle: true,
          leading: IconButton(
            icon: const Icon(Icons.arrow_back_ios),
            color: Colors.black,
            onPressed: () => Navigator.pop(context),
          ),
          actions: [
            Container(
              margin: const EdgeInsets.only(right: 16),
              height: 36,
              decoration: BoxDecoration(
                border: Border.all(
                  color: BaseColor.second400,
                  width: 1,
                ),
                borderRadius: BorderRadius.circular(18),
                color: Colors.white,
              ),
              child: TextButton.icon(
                onPressed: () {
                  // Xử lý mở màn hình hỗ trợ hoặc gọi hotline...
                },
                icon: const Icon(Icons.headset_mic, size: 18, color: BaseColor.second600,),
                label: const Text("Hỗ trợ"),
                style: TextButton.styleFrom(
                  foregroundColor: BaseColor.second600,
                  padding: const EdgeInsets.symmetric(horizontal: 8),
                ),
              ),
            ),
          ],
        ),
        backgroundColor: Colors.white,
        body: SafeArea(
          child: Stack(
            children: [
              // Nội dung cuộn ở dưới
              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 Obx(() {
      return RichText(
        text: TextSpan(
          style: const TextStyle(fontSize: 14, color: BaseColor.second500),
          children: [
            const TextSpan(text: "Chào mừng "),
            TextSpan(text: "${vm.userName}"),
            const TextSpan(text: " "),
            TextSpan(
              text: "${vm.phoneNumber}",
              style: const TextStyle(fontWeight: FontWeight.w500, color: BaseColor.primary500),
            ),
          ],
        ),
      );
    });
  }

  Widget _buildPasswordField(LoginViewModel vm) {
    return Obx(() {
      return TextField(
        controller: _phoneController,
        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: BorderSide(color: Colors.red), //BaseColor.second200),
          ),
          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,
          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(Get.context!)),
          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 : null,
          child: const Text(
            "Đăng nhập",
            style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: Colors.white),
          ),
        ),
      );
    });
  }
}
