import 'package:flutter/material.dart';
import 'package:flutter_widget_from_html/flutter_widget_from_html.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/screen/register_campaign/register_form_input_viewmodel.dart';
import '../../resources/base_color.dart';
import '../../shared/router_gage.dart';
import '../../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 StatefulWidget {
  const RegisterFormInputScreen({super.key});

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

class _RegisterFormInputScreenState extends State<RegisterFormInputScreen> {
  late final RegisterFormInputViewModel _viewModel;
  String _title = '';
  final _isFormValid = false.obs;
  late var _isConfirmScreen = false;

  @override
  void initState() {
    super.initState();
    _viewModel = Get.put(RegisterFormInputViewModel());

    final args = Get.arguments as Map<String, dynamic>?;
    if (args?['formConfirm'] != null) {
      _isConfirmScreen = true;
      final data = args!['formConfirm'] as RegistrationFormPackageModel;
      _title = data?.formConfirm?.title ?? '';
      _viewModel.form.value = data;
    } else {
      final id = (args?['product'] as ProductModel?)?.id;
      if (id != null) {
        _isConfirmScreen = false;
        _viewModel.fetchRegisterFormInput(id.toString()).then((_) {
          setState(() {
            _title = _viewModel.form.value?.title ?? '';
          });
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    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: _gotoPaymentScreen,
                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() {
    print("_gotoPaymentScreen");
  }

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

  void _validateForm() {
    final form = _viewModel.form.value?.formRegistration;
    final inputs = form?.inputRequired ?? [];
    inputs.forEach((input) {
      print("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;
  }
}
