import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pin_code_fields/pin_code_fields.dart';
import '../../resouce/base_color.dart';
import 'otp_view_model.dart';

class OtpScreen extends StatefulWidget {
  final IOtpRepository repository;

  const OtpScreen({super.key, required this.repository});

  @override
  State<OtpScreen> createState() => _OtpScreenState();
}

class _OtpScreenState extends State<OtpScreen> {
  @override
  Widget build(BuildContext context) {
    final otpVM = Get.put(OtpViewModel(widget.repository));

    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        leading: IconButton(icon: const Icon(Icons.arrow_back_ios), onPressed: () => Navigator.pop(context)),
      ),
      body: SafeArea(
        child: GestureDetector(
          onTap: () => FocusScope.of(context).unfocus(),
          child: SingleChildScrollView(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                const Text("Nhập mã xác thực OTP", style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold)),
                const SizedBox(height: 12),
                _buildWelcomeText(otpVM),
                const SizedBox(height: 32),
                _buildPinCodeFields(otpVM),
                const SizedBox(height: 16),
                _buildErrorText(otpVM),
                const SizedBox(height: 16),
                _buildResendOtp(otpVM),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// PinCodeTextField cho 6 ô
  Widget _buildPinCodeFields(OtpViewModel vm) {
    double screenWidth = MediaQuery.of(context).size.width;
    // return Obx(() {
    return PinCodeTextField(
      appContext: Get.context!,
      length: 6,
      obscureText: false,
      cursorColor: Colors.black,
      keyboardType: TextInputType.number,
      autoFocus: true,
      animationType: AnimationType.none,
      pinTheme: PinTheme(
        shape: PinCodeFieldShape.box,
        borderRadius: BorderRadius.circular(6),
        fieldHeight: screenWidth / 6 - 12,
        fieldWidth: screenWidth / 6 - 12,
        activeColor: Colors.blue,
        inactiveColor: Colors.grey.shade300,
        selectedColor: Colors.blueAccent,
      ),
      onChanged: (value) {
        vm.otpCode.value = value;
        vm.errorMessage.value = ""; // clear lỗi khi gõ
      },
      onCompleted: (value) {
        vm.otpCode.value = value;
      },
    );
    // });
  }

  Widget _buildErrorText(OtpViewModel vm) {
    // Chỉ bọc Obx ở đây vì ta đọc vm.errorMessage
    return Obx(() {
      final error = vm.errorMessage.value;
      if (error.isEmpty) {
        return const SizedBox.shrink();
      }
      return Text(error, style: const TextStyle(color: Colors.red));
    });
  }

  /// "Gửi lại OTP (02:30)"
  Widget _buildResendOtp(OtpViewModel vm) {
    // Bọc Obx vì ta đọc vm.currentCountdown
    return Obx(() {
      final cd = vm.currentCountdown.value;
      final canResend = cd == 0;
      final textTime = vm.countdownText;
      return Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          TextButton(
            onPressed: canResend ? vm.onResendOtp : null,
            child: Text(
              "Gửi lại OTP ${!canResend ? "($textTime)" : ""}",
              style: TextStyle(color: canResend ? Colors.blue : Colors.grey),
            ),
          ),
        ],
      );
    });
  }

  Widget _buildWelcomeText(OtpViewModel vm) {
    return RichText(
      text: TextSpan(
        style: TextStyle(fontSize: 14, color: BaseColor.second500),
        children: [
          const TextSpan(text: "Mã OTP đã được gửi về số điện thoại "),
          TextSpan(
            text: "0999999999", //"${vm.phoneNumber}",
            style: const TextStyle(fontWeight: FontWeight.w500, color: BaseColor.primary500),
          ),
        ],
      ),
    );
  }
}
