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/shared/router_gage.dart';
import '../../base/base_screen.dart';
import '../../base/basic_state.dart';
import '../../resources/base_color.dart';
import '../faqs/faqs_screen.dart';
import '../otp/otp_screen.dart';
import '../otp/verify_otp_repository.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.put(OnboardingViewModel());
  final FocusNode _focusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    _viewModel.onShowAlertError = (message) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        showAlertError(content: message);
      });
    };
    _viewModel.fetchOnboardingContent();
  }

  @override
  Widget createBody() {
    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
                                        ? () {
                                      hideKeyboard();
                                      _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.toNamed(campaignDetailScreen, arguments: {"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),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
