import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pin_code_fields/pin_code_fields.dart';
import '../../base/base_screen.dart';
import '../../base/basic_state.dart';
import '../../resources/base_color.dart';
import '../../widgets/back_button.dart';
import '../../widgets/support_button.dart';
import 'otp_viewmodel.dart';

class OtpScreen extends BaseScreen {
  final IOtpRepository repository;
  const OtpScreen({super.key, required this.repository});

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

class _OtpScreenState extends BaseState<OtpScreen> with BasicState {
  final TextEditingController _pinController = TextEditingController();

  @override
  void initState() {
    super.initState();
    final OtpViewModel otpVM = Get.put(OtpViewModel(widget.repository));
    ever(otpVM.errorMessage, (value) {
      if (value != null && value.toString().isNotEmpty) {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          showAlertError(content: value);
        });
      }
    });
  }

  @override
  Widget createBody() {
    final otpVM = Get.put(OtpViewModel(widget.repository));
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        leading: CustomBackButton(),
        actions: [
          SupportButton(),
        ],
      ),
      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: 32, 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),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildPinCodeFields(OtpViewModel vm) {
    double screenWidth = MediaQuery.of(context).size.width;
      return PinCodeTextField(
        controller: _pinController,
        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 = "";
        },
        onCompleted: (value) {
          vm.otpCode.value = value;
          vm.onSubmitOtp();
        },
      );
  }

  Widget _buildErrorText(OtpViewModel vm) {
    return Obx(() {
      final error = vm.errorMessage.value;
      if (error.isEmpty) {
        return const SizedBox.shrink();
      }
      return Text(error, style: const TextStyle(color: Colors.red));
    });
  }

  Widget _buildResendOtp(OtpViewModel vm) {
    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,
              vm.otpCode.value = "",
              vm.errorMessage.value = "",
              _pinController.clear(),
            },
            child: Text(
              "Gửi lại OTP ${!canResend ? "($textTime)" : ""}",
              style: TextStyle(color: canResend ? BaseColor.second700 : BaseColor.second500),
            ),
          ),
        ],
      );
    });
  }

  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: widget.repository.phoneNumber,
            style: const TextStyle(fontWeight: FontWeight.w500, color: BaseColor.primary500),
          ),
        ],
      ),
    );
  }
}
