import 'package:flutter/material.dart';
import 'package:flutter_widget_from_html_core/flutter_widget_from_html_core.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/features/register_campaign/register_form_input_viewmodel.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/router_gage.dart';
import '../../shared/widgets/custom_navigation_bar.dart';
import '../voucher/models/product_model.dart';
import 'input_form_cell.dart';
import 'model/registration_form_package_model.dart';

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

  @override
  State<RegisterFormInputScreen> createState() => _RegisterFormInputScreenState();
}

class _RegisterFormInputScreenState extends BaseState<RegisterFormInputScreen> with BasicState {
  late final RegisterFormInputViewModel _viewModel;
  String _title = '';
  final _isFormValid = false.obs;
  late var _isConfirmScreen = false;
  ProductModel? _product;

  @override
  void initState() {
    super.initState();
    _viewModel = Get.put(RegisterFormInputViewModel());
    _viewModel.onShowAlertError = (message) {
      showAlertError(content: message);
    };
    _viewModel.verifyRegisterFormSuccess = (data) {
      final alert = data.alert;
      final des = alert?.description ?? '';
      if (alert?.alert == true && des.isNotEmpty) {
        showAlertError(content: des, onConfirmed: () {
          _gotoPaymentScreen();
        });
      } else {
        _gotoPaymentScreen();
      }
    };

    final args = Get.arguments as Map<String, dynamic>?;
    _product = args?['product'] as ProductModel?;

    if (args?['formConfirm'] != null) {
      _isConfirmScreen = true;
      final data = args?['formConfirm'] as RegistrationFormPackageModel;
      _title = data.formConfirm?.title ?? '';
      _viewModel.form.value = data;
    } else {
      _isConfirmScreen = false;
      final id = _product?.id.toString() ?? '';
      if (id.isEmpty) return;
      _viewModel.fetchRegisterFormInput(id).then((_) {
        setState(() {
          _title = _viewModel.form.value?.title ?? '';
        });
      });
    }
  }

  @override
  Widget createBody() {
    return GestureDetector(
      onTap: () => FocusScope.of(context).unfocus(),
      child: Scaffold(
        appBar: CustomNavigationBar(title: _title),
        body: Obx(() {
          final form = _isConfirmScreen ? _viewModel.form.value?.formConfirm : _viewModel.form.value?.formRegistration;
          final inputItem = _viewModel.form.value?.formRegistration?.inputRequired;
          _validateForm();
          if (form == null) {
            return const Center(child: CircularProgressIndicator());
          }
          return SingleChildScrollView(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // Header HTML
                if (form.headerDescription?.title?.isNotEmpty == true)
                  Container(
                    color: BaseColor.primary50,
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: HtmlWidget(form.headerDescription!.title!),
                    ),
                  ),
                const SizedBox(height: 12),
                // Inputs
                if (inputItem != null)
                  ...inputItem.map(
                    (item) => Padding(
                      padding: const EdgeInsets.only(bottom: 16),
                      child: InputFormCell(model: item, onChanged: _validateForm, isViewOnly: _isConfirmScreen),
                    ),
                  ),

                // Footer HTML + Checkbox nếu có
                if (form.footerDescription?.title?.isNotEmpty == true)
                  Padding(
                    padding: const EdgeInsets.only(top: 16),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        if (form.checked == true && _isConfirmScreen == false)
                          Obx(
                            () => Checkbox(
                              activeColor: BaseColor.primary400,
                              value: _viewModel.isChecked.value,
                              onChanged: (val) {
                                _viewModel.isChecked.value = val ?? false;
                                _validateForm();
                              },
                            ),
                          ),
                        Expanded(child:
                        GestureDetector(
                            onTap: () {
                              form.footerDescription?.directional?.begin();
                            },
                            child: HtmlWidget(form.footerDescription!.title!)),
                        ),
                      ],
                    ),
                  ),
                const SizedBox(height: 24),
                _buildBottomButton(),
              ],
            ),
          );
        }),
      ),
    );
  }

  Widget _buildBottomButton() {
    if (_isConfirmScreen) {
      return SizedBox(
        width: double.infinity,
        child: Row(
          mainAxisSize: MainAxisSize.max,
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            Expanded(
              child: OutlinedButton(
                onPressed: () {
                  Navigator.pop(context);
                },
                style: OutlinedButton.styleFrom(
                  side: const BorderSide(color: Colors.black54),
                  padding: const EdgeInsets.symmetric(vertical: 14),
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                ),
                child: const Text("Chỉnh sửa", style: TextStyle(color: Colors.black, fontSize: 16)),
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: ElevatedButton(
                onPressed: _continueToPaymentHandle,
                style: ElevatedButton.styleFrom(
                  backgroundColor: BaseColor.primary400,
                  padding: const EdgeInsets.symmetric(vertical: 14),
                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                ),
                child: const Text("Tiếp tục", style: TextStyle(color: Colors.white, fontSize: 16)),
              ),
            ),
          ],
        ),
      );
    }
    return SizedBox(
      width: double.infinity,
      child: Obx(
        () => ElevatedButton(
          onPressed: _isFormValid.value ? _onSubmit : null,
          style: ElevatedButton.styleFrom(
            backgroundColor: BaseColor.primary400,
            padding: const EdgeInsets.symmetric(vertical: 14),
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
          ),
          child: const Text("Tiếp tục", style: TextStyle(color: Colors.white, fontSize: 16)),
        ),
      ),
    );
  }

  void _gotoPaymentScreen() {
    final metaData = (_viewModel.form.value?.submitParams ?? {}).toJsonString();
    debugPrint("_gotoPaymentScreen metaData $metaData");
    Get.toNamed(transactionDetailScreen, arguments: {"product": _product, "quantity": 1, "metaData": metaData});
  }

  void _onSubmit() {
    if (_viewModel.form.value?.formConfirm?.checked == true) {
      Get.toNamed(registerFormInputScreen, arguments: {"formConfirm": _viewModel.form.value, "product": _product}, preventDuplicates: false);
    } else {
      _continueToPaymentHandle();
    }
  }

  void _continueToPaymentHandle() {
    if (_viewModel.verifyUrl.isNotEmpty) {
      _viewModel.verifyRegisterForm();
    } else {
      _gotoPaymentScreen();
    }
  }

  void _validateForm() {
    final form = _viewModel.form.value?.formRegistration;
    final inputs = form?.inputRequired ?? [];
    for (var input in inputs) {
      debugPrint("Input: ${input.title}, Value: ${input.value}");
    }
    final isValid = inputs.every((input) {
      if (input.require == true) {
        return input.value.trim().isNotEmpty == true;
      }
      return true;
    });
    final isChecked = _viewModel.isChecked.value;
    _isFormValid.value = isValid && isChecked;
  }
}
