import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_widget_from_html/flutter_widget_from_html.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/base/base_response_model.dart';
import '../../base/base_screen.dart';
import '../../base/basic_state.dart';
import '../../configs/constants.dart';
import '../../resouce/base_color.dart';
import '../biometric/biometric_screen.dart';
import '../faqs/faqs_screen.dart';
import '../login/login_screen.dart';
import '../otp/otp_screen.dart';
import '../otp/verify_otp_repository.dart';
import '../pageDetail/campaign_detail_screen.dart';
import '../pageDetail/model/detail_page_rule_type.dart';
import 'model/check_phone_response_model.dart';
import 'onboarding_viewmodel.dart';

class OnboardingScreen extends BaseScreen {
  const OnboardingScreen({super.key});

  @override
  State<OnboardingScreen> createState() => _OnboardingScreenState();
}

class _OnboardingScreenState extends BaseState<OnboardingScreen> with BasicState {
  final OnboardingViewModel _viewModel = Get.find<OnboardingViewModel>();
  final FocusNode _focusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    _viewModel.fetchOnboardingContent();
    _viewModel.checkPhoneRes.listen((response) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        hideKeyboard();
        _handleResponseCheckPhoneNumber(response.data);
        _handleResponseError(response);
      });
    });
  }

  void _handleResponseError(BaseResponseModel<CheckPhoneResponseModel>? response) {
    if (response?.isSuccess ?? false) return;
    var errorCode = response?.errorCode ?? "";
    var errorMessage = response?.errorMessage ?? Constants.commonError;
    WidgetsBinding.instance.addPostFrameCallback((_) {
      showAlertError(content: errorMessage);
      if (errorCode == ErrorCodes.deviceLock) {
        // show alert error popupErrorCSKH
        return;
      }      //show alert error popupError
    });
  }

  void _handleResponseCheckPhoneNumber(CheckPhoneResponseModel? response) {
    if (response == null) return;
    if (response.requireRecaptcha == true) return;

    if ((response.mfaToken ?? "").isNotEmpty || (response.nextAction == "signup")) {
      // show OTP
      Get.to(
        () => OtpScreen(
          repository: VerifyOtpRepository(
            _viewModel.phoneNumber.value,
            response?.otpTtl ?? 0,
            response?.mfaToken ?? "",
          ),
        ),
      );
      return;
    }
    if (response.nextAction == "login") {
      Get.to(() => LoginScreen(phoneNumber: _viewModel.phoneNumber.value));
    }
  }

  @override
  Widget createBody() {
    final double keyboardHeight = MediaQuery.of(context).viewInsets.bottom;
    return GestureDetector(
      onTap: hideKeyboard,
      child: Scaffold(
        resizeToAvoidBottomInset: false,
        body: Stack(
          children: [
            Obx(
              () => Positioned.fill(
                child:
                    _viewModel.url.isNotEmpty
                        ? Image.network(_viewModel.url, fit: BoxFit.cover)
                        : Image.asset("assets/images/bg_onboarding.png", fit: BoxFit.cover),
              ),
            ),
            SafeArea(
              child: Column(
                children: [
                  Spacer(),
                  AnimatedContainer(
                    duration: const Duration(milliseconds: 300),
                    padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 32),
                    child: SingleChildScrollView(
                      keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
                      physics: BouncingScrollPhysics(),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Obx(
                            () => Visibility(
                              visible: !_focusNode.hasFocus,
                              child: HtmlWidget(
                                _viewModel.content.isNotEmpty
                                    ? _viewModel.content
                                    : """<h4 style="color: white;">Tiêu điểm dễ - Trừ tiền mê</h4>
                                       <p style="color: white;">Đừng bỏ lỡ cơ hội tích tới 30% tất cả giao dịch viễn thông 
                                       của các nhà mạng và đổi phiếu giảm giá tại hơn 200 thương hiệu được yêu thích nhất.</p>""",
                                textStyle: TextStyle(color: Colors.white),
                              ),
                            ),
                          ),
                          const SizedBox(height: 16),
                          TextField(
                            inputFormatters: [LengthLimitingTextInputFormatter(10)],
                            // maxLength: 10,
                            focusNode: _focusNode,
                            keyboardType: TextInputType.phone,
                            style: const TextStyle(color: BaseColor.second600),
                            decoration: InputDecoration(
                              filled: true,
                              fillColor: Colors.white,
                              hintText: "Nhập số điện thoại",
                              hintStyle: const TextStyle(color: Colors.grey),
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(10),
                                borderSide: BorderSide.none,
                              ),
                              prefixIcon: const Icon(Icons.phone, color: Color(0xFF9DA4AE)),
                            ),
                            onChanged: _viewModel.updatePhoneNumber,
                          ),
                          const SizedBox(height: 16),
                          Obx(
                            () => SizedBox(
                              width: double.infinity,
                              child: ElevatedButton(
                                onPressed:
                                    _viewModel.isButtonEnabled
                                        ? () {
                                          _viewModel.checkPhoneNumber();
                                        }
                                        : null,
                                style: ElevatedButton.styleFrom(
                                  padding: const EdgeInsets.symmetric(vertical: 15),
                                  backgroundColor: _viewModel.isButtonEnabled ? Colors.white : Colors.white54,
                                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                                ),
                                child: Text(
                                  "Tiếp tục",
                                  style: TextStyle(
                                    color: _viewModel.isButtonEnabled ? BaseColor.second600 : BaseColor.second400,
                                    fontSize: 18,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ),
                            ),
                          ),
                          const SizedBox(height: 16),
                          Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Obx(
                                () => Checkbox(
                                  value: _viewModel.isChecked.value,
                                  onChanged: _viewModel.toggleCheckbox,
                                  activeColor: Colors.white,
                                  checkColor: Colors.red,
                                  side: const BorderSide(color: Colors.white, width: 2),
                                ),
                              ),
                              Expanded(
                                child: RichText(
                                  text: TextSpan(
                                    style: const TextStyle(color: Colors.white, fontSize: 14),
                                    children: [
                                      const TextSpan(text: "Bằng việc tiếp tục, bạn đã đọc và đồng ý với "),
                                      WidgetSpan(
                                        child: GestureDetector(
                                          onTap: () => Get.to(CampaignDetailScreen(type: DetailPageRuleType.termsOfUse)),
                                          child: const Text(
                                            "Điều khoản sử dụng",
                                            style: TextStyle(
                                              decoration: TextDecoration.underline,
                                              decorationColor: Colors.white,
                                              decorationThickness: 2,
                                              color: Colors.white,
                                            ),
                                          ),
                                        ),
                                      ),
                                      const TextSpan(text: " và "),
                                      WidgetSpan(
                                        child: GestureDetector(
                                          onTap: () => Get.to(FAQScreen()),// Get.to(CampaignDetailScreen(type: DetailPageRuleType.privacyPolicy)),
                                          child: const Text(
                                            "Chính sách bảo mật",
                                            style: TextStyle(
                                              decoration: TextDecoration.underline,
                                              decorationColor: Colors.white,
                                              decorationThickness: 2,
                                              color: Colors.white,
                                            ),
                                          ),
                                        ),
                                      ),
                                      const TextSpan(text: " của MyPoint"),
                                    ],
                                  ),
                                ),
                              ),
                            ],
                          ),
                          SizedBox(height: 0),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
