import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pin_code_fields/pin_code_fields.dart';
import '../../shared/widgets/base_view/base_screen.dart';
import '../../shared/widgets/base_view/basic_state.dart';
import '../../core/theme/base_color.dart';
import '../../shared/widgets/back_button.dart';
import '../../shared/widgets/custom_navigation_bar.dart';
import '../../shared/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();
  late final OtpViewModel _otpVM;

  @override
  void initState() {
    super.initState();
    Get.delete<OtpViewModel>(force: true);
    _otpVM = Get.put(OtpViewModel(widget.repository));
    ever(_otpVM.errorMessage, (value) {
      if (value.toString().isNotEmpty) {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          showAlertError(content: value);
        });
      }
    });
  }

  @override
  Widget createBody() {
    return Scaffold(
      appBar: CustomNavigationBar(
        title: '',
        backgroundImage: '',
        leftButtons: [CustomBackButton()],
        rightButtons: [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),
          ),
        ],
      ),
    );
  }
}
