import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:niogu_ecommerce_v1/core/constant/app_color.dart';
import 'package:niogu_ecommerce_v1/core/constant/app_font_size.dart';
import 'package:niogu_ecommerce_v1/core/errors/exceptions.dart';
import 'package:niogu_ecommerce_v1/core/utils/log_message.dart';
import 'package:niogu_ecommerce_v1/core/widgets/custom_snackbar.dart';
import 'package:niogu_ecommerce_v1/core/widgets/custom_text_form_field.dart';
import 'package:niogu_ecommerce_v1/features/account/presentation/providers/account_provider.dart';
import 'package:sizer/sizer.dart';

class ChangePasswordScreen extends ConsumerStatefulWidget {
  const ChangePasswordScreen({super.key});

  @override
  ConsumerState<ChangePasswordScreen> createState() =>
      _ChangePasswordScreenState();
}

class _ChangePasswordScreenState extends ConsumerState<ChangePasswordScreen> {
  final _formKey = GlobalKey<FormState>();

  final _oldPasswordController = TextEditingController();

  final _newPasswordController = TextEditingController();

  final _confirmPasswordController = TextEditingController();

  bool _obsecureOldPassword = true;

  bool _obsecureNewPassword = true;

  bool _obsecureConfirmPassword = true;

  @override
  void dispose() {
    _oldPasswordController.dispose();
    _newPasswordController.dispose();
    _confirmPasswordController.dispose();
    super.dispose();
  }

  String? _validation({
    String? value,
    required String message,
    bool isNewPassword = false,
    bool isPasswordConfirm = false,
  }) {
    if (value == null || value.isEmpty) {
      return message;
    }

    if (isNewPassword) {
      if (value.length < 8) {
        return "Password minimal harus 8 karakter";
      }

      final passwordRegExp = RegExp(
        r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&#])[A-Za-z\d@$!%*?&#]{8,}$',
      );

      if (!passwordRegExp.hasMatch(value)) {
        return "Gunakan huruf besar, kecil, angka, dan simbol";
      }
    }

    if (isPasswordConfirm && value != _newPasswordController.text.trim()) {
      return "Konfirmasi password tidak sesuai";
    }

    return null;
  }

  Future<void> _updatePassword() async {
    if (!_formKey.currentState!.validate()) return;

    try {
      await ref
          .read(customerControllerProvider.notifier)
          .updatePassword(
            oldPassword: _oldPasswordController.text.trim(),
            newPassword: _newPasswordController.text.trim(),
          );

      if (!mounted) return;

      CustomSnackbar.showSuccess(context, "Password berhasil diubah");
      context.pop();
    } on ServerException catch (e, st) {
      LogMessage.log.e(e.toString(), error: e, stackTrace: st);
      CustomSnackbar.showError(context, e.message);
    }
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final customerState = ref.watch(customerControllerProvider);
        return SafeArea(
          top: false,
          bottom: true,
          right: false,
          left: false,
          child: Scaffold(
            backgroundColor: Colors.white,
            appBar: AppBar(
              backgroundColor: Colors.white,
              elevation: 0.5,
              leading: IconButton(
                icon: Icon(
                  Icons.arrow_back,
                  color: AppColor.primaryColor,
                  size: 7.w,
                ),
                onPressed: () => context.pop(),
              ),
              title: Text(
                "Ubah Password",
                style: TextStyle(
                  color: Colors.black,
                  fontSize: AppFontSize.medium.sp,
                  fontWeight: FontWeight.bold,
                ),
              ),
              centerTitle: true,
            ),
            body: SingleChildScrollView(
              padding: EdgeInsets.all(5.w),
              child: Form(
                key: _formKey,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _buildInfoSection(),
                    SizedBox(height: 4.h),

                    CustomTextFormField(
                      label: "Password Lama",
                      hint: "Masukkan password lama",
                      controller: _oldPasswordController,
                      isObscure: _obsecureOldPassword,
                      prefixIcon: Icons.lock_outline,
                      suffixIcon: _obsecureOldPassword
                          ? Icons.visibility
                          : Icons.visibility_off,
                      suffixPressed: () {
                        setState(() {
                          _obsecureOldPassword = !_obsecureOldPassword;
                        });
                      },
                      validator: (value) => _validation(
                        value: value,
                        message: "Password lama belum diisi",
                      ),
                    ),

                    SizedBox(height: 3.h),

                    CustomTextFormField(
                      label: "Password Baru",
                      hint: "Masukkan password baru",
                      controller: _newPasswordController,
                      isObscure: _obsecureNewPassword,
                      prefixIcon: Icons.lock_reset_outlined,
                      suffixIcon: _obsecureOldPassword
                          ? Icons.visibility
                          : Icons.visibility_off,
                      suffixPressed: () {
                        setState(() {
                          _obsecureNewPassword = !_obsecureNewPassword;
                        });
                      },
                      validator: (value) => _validation(
                        value: value,
                        message: "Password baru belum diisi",
                        isNewPassword: true,
                      ),
                    ),

                    SizedBox(height: 3.h),

                    CustomTextFormField(
                      label: "Konfirmasi Password Baru",
                      hint: "Konfirmasi password baru",
                      controller: _confirmPasswordController,
                      isObscure: _obsecureConfirmPassword,
                      prefixIcon: Icons.check_circle_outline,
                      suffixIcon: _obsecureOldPassword
                          ? Icons.visibility
                          : Icons.visibility_off,
                      suffixPressed: () {
                        setState(() {
                          _obsecureConfirmPassword = !_obsecureConfirmPassword;
                        });
                      },
                      validator: (value) => _validation(
                        value: value,
                        message: "Konfirmasi password belum diisi",
                        isPasswordConfirm: true,
                      ),
                    ),

                    SizedBox(height: 6.h),

                    SizedBox(
                      width: double.infinity,
                      child: ElevatedButton(
                        onPressed: customerState.isLoading
                            ? null
                            : _updatePassword,
                        style: ElevatedButton.styleFrom(
                          backgroundColor: AppColor.primaryColor,
                          padding: EdgeInsets.symmetric(vertical: 2.h),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(3.w),
                          ),
                          elevation: 0,
                        ),
                        child: Text(
                          "Simpan Perubahan",
                          style: TextStyle(
                            fontSize: AppFontSize.medium.sp,
                            fontWeight: FontWeight.bold,
                            color: Colors.white,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  Widget _buildInfoSection() {
    return Container(
      padding: EdgeInsets.all(4.w),
      decoration: BoxDecoration(
        color: AppColor.primaryColor.withOpacity(0.1),
        borderRadius: BorderRadius.circular(2.w),
      ),
      child: Row(
        children: [
          Icon(Icons.info_outline, color: AppColor.primaryColor, size: 5.w),
          SizedBox(width: 3.w),
          Expanded(
            child: Text(
              "Gunakan minimal 8 karakter dengan kombinasi huruf dan angka untuk password yang kuat.",
              style: TextStyle(
                fontSize: (AppFontSize.small - 1.25).sp,
                color: AppColor.primaryColor,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
