import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/features/create_pass/signup_create_password_repository.dart';
import 'package:mypoint_flutter_app/shared/widgets/back_button.dart';
import '../../app/config/constants.dart';
import '../../core/theme/base_color.dart';
import 'create_pass_viewmodel.dart';

class CreatePasswordScreen extends StatelessWidget {
  final ICreatePasswordRepository repository;

  const CreatePasswordScreen({super.key, required this.repository});

  @override
  Widget build(BuildContext context) {
    final vm = Get.put(CreatePasswordViewModel(repository));
    final isNewPassObscure = true.obs;
    final isConfirmPassObscure = true.obs;
    final topExpand = MediaQuery.of(context).padding.top + 8 + Constants.extendTopPaddingNavigation;

    return Scaffold(
      body: SafeArea(
        top: false,
        child: Stack(
          children: [
            GestureDetector(
              onTap: () => FocusScope.of(context).unfocus(),
              child: SingleChildScrollView(
                padding: EdgeInsets.only(left: 16, right: 16, top: 16 + topExpand + 36), //all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    const Text("Tạo mật khẩu", style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold)),
                    const SizedBox(height: 32),
                    Obx(() {
                      return _buildPasswordField(
                        hintText: "Nhập mật khẩu mới",
                        obscureText: isNewPassObscure.value,
                        onToggleObscure: () => isNewPassObscure.value = !isNewPassObscure.value,
                        onChanged: vm.onNewPasswordChanged,
                      );
                    }),
                    const SizedBox(height: 16),
                    Obx(() {
                      return _buildPasswordField(
                        hintText: "Xác nhận lại mật khẩu",
                        obscureText: isConfirmPassObscure.value,
                        onToggleObscure: () => isConfirmPassObscure.value = !isConfirmPassObscure.value,
                        onChanged: vm.onConfirmPasswordChanged,
                      );
                    }),
                    const SizedBox(height: 8),
                    Obx(() {
                      final err = vm.errorMessage.value;
                      if (err.isEmpty) {
                        return const SizedBox.shrink();
                      } else {
                        return Text(err, style: const TextStyle(color: Colors.red));
                      }
                    }),
                    Obx(() {
                      return Column(
                        crossAxisAlignment: CrossAxisAlignment.stretch,
                        children: [
                          const SizedBox(height: 8),
                          _buildInfoGuide(icon: Icons.info_outline, text: "Mật khẩu gồm 6 chữ số", isValidate: vm.isSixDigits.value),
                          const SizedBox(height: 4),
                          _buildInfoGuide(icon: Icons.info_outline, text: "Không bao gồm dãy số trùng nhau", isValidate: vm.isNotRepeatedSequence.value),
                          const SizedBox(height: 4),
                          _buildInfoGuide(icon: Icons.info_outline, text: "Không bao gồm dãy số liên tiếp", isValidate: vm.isNotSequential.value),
                        ],
                      );
                    }),
                  ],
                ),
              ),
            ),
            SizedBox.expand(),
            Positioned(left: 0, right: 0, bottom: 16, child: _buildContinueButton(vm)),
            Positioned(top: topExpand, left: 8, child: CustomBackButton()),
          ],
        ),
      ),
    );
  }

  Widget _buildContinueButton(CreatePasswordViewModel vm) {
    return Obx(() {
      final enabled = vm.isButtonEnabled.value;
      return Container(
        color: Colors.white,
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        child: ElevatedButton(
          onPressed: enabled ? vm.onSubmit : null,
          style: ElevatedButton.styleFrom(
            minimumSize: const Size.fromHeight(48),
            backgroundColor: enabled ? BaseColor.primary500 : BaseColor.second400,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
          ),
          child: Text(
            "Tiếp tục",
            style: TextStyle(color: enabled ? Colors.white : Colors.white, fontWeight: FontWeight.bold, fontSize: 16),
          ),
        ),
      );
    });
  }

  Widget _buildInfoGuide({required IconData icon, required String text, required bool isValidate}) {
    final color = isValidate ? BaseColor.second400 : BaseColor.primary300;
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Icon(icon, color: color, size: 24),
        SizedBox(width: 8),
        Expanded(child: Text(text, style: TextStyle(color: color, fontSize: 14))),
      ],
    );
  }

  Widget _buildPasswordField({
    required String hintText,
    required bool obscureText,
    required VoidCallback onToggleObscure,
    required ValueChanged<String> onChanged,
  }) {
    return TextField(
      keyboardType: TextInputType.number,
      inputFormatters: [
        FilteringTextInputFormatter.digitsOnly,
        LengthLimitingTextInputFormatter(6),
      ],
      obscureText: obscureText,
      onChanged: onChanged,
      decoration: InputDecoration(
        prefixIcon: const Icon(Icons.password, color: BaseColor.second500),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8),
          borderSide: const BorderSide(color: Colors.grey, width: 1),
        ),
        enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8),
          borderSide: const BorderSide(color: Colors.grey, width: 1),
        ),
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8),
          borderSide: const BorderSide(color: Colors.grey, width: 1),
        ),
        hintText: hintText,
        hintStyle: const TextStyle(color: BaseColor.second200),
        fillColor: Colors.white,
        filled: true,
        contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 14),
        suffixIcon: IconButton(
          icon: Icon(obscureText ? Icons.visibility_off : Icons.visibility, color: BaseColor.second500),
          onPressed: onToggleObscure,
        ),
      ),
    );
  }
}
