import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:niogu_app/core/components/top_back_bar_app.dart';
import 'package:niogu_app/core/constants/app_color.dart';
import 'package:niogu_app/core/constants/app_font_size.dart';
import 'package:niogu_app/core/utils/log_message.dart';
import 'package:niogu_app/core/widgets/custom_snackbar.dart';
import 'package:niogu_app/core/widgets/custom_text_form_field.dart';
import 'package:niogu_app/features/profile/presentation/providers/profile_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 _newPasswordConfirmController = TextEditingController();

  bool _obscureOld = true;

  bool _obscureNew = true;

  bool _obscureConfirm = true;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _oldPasswordController.dispose();
    _newPasswordController.dispose();
    _newPasswordConfirmController.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;

    final validatePassword = await ref
        .read(profileRepositoryProvider)
        .validatePassword(_oldPasswordController.text.trim());

    if (!validatePassword) {
      CustomSnackbar.showError(context, "Password lama tidak valid");
      return;
    }

    try {
      await ref
          .read(profileControllerProvider.notifier)
          .updatePassword(_newPasswordController.text.trim());

      if (!mounted) return;

      CustomSnackbar.showSuccess(context, "Password berhasil diubah");
      context.pop();
    } catch (e, st) {
      LogMessage.log.e(e.toString(), error: e, stackTrace: st);
      CustomSnackbar.showError(context, 'Ups, terjadi kesalahan');
    }
  }

  @override
  Widget build(BuildContext context) {
    final bool isTablet = 100.w >= 600;

    final profileControllerState = ref.watch(profileControllerProvider);

    return Scaffold(
      backgroundColor: const Color(0xFFF9FAFB),
      appBar: TopBackBarApp(title: "Ubah Password", onTap: () => context.pop()),
      body: SingleChildScrollView(
        padding: EdgeInsets.all(5.w),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              /**
              Container(
                padding: EdgeInsets.all(4.w),
                decoration: BoxDecoration(
                  color: Colors.blue[50],
                  borderRadius: BorderRadius.circular(2.5.w),
                  border: Border.all(color: Colors.blue.shade100),
                ),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Icon(
                      Icons.info_outline,
                      color: Colors.blue[700],
                      size: 5.w,
                    ),
                    SizedBox(width: 3.w),
                    Expanded(
                      child: Text(
                        "Demi keamanan akun, password hanya dapat diubah setiap 30 hari sekali. Gunakan password yang kuat dan mudah diingat",
                        style: TextStyle(
                          color: Colors.blue[900],
                          fontSize: isTablet
                              ? (AppFontSize.medium - 1.25).sp
                              : (AppFontSize.small - 1.25).sp,
                        ),
                      ),
                    ),
                  ],
                ),
              ),

              SizedBox(height: 3.h),
              */
              CustomTextFormField(
                label: "Password Lama",
                hint: "••••••••",
                controller: _oldPasswordController,
                isObscure: _obscureOld,
                suffixIcon: _obscureOld
                    ? Icons.visibility_off
                    : Icons.visibility,
                suffixPressed: () => setState(() => _obscureOld = !_obscureOld),
                validator: (value) => _validation(
                  value: value,
                  message: "Password lama belum diisi",
                ),
              ),

              SizedBox(height: 2.h),

              CustomTextFormField(
                label: "Password Baru",
                hint: "••••••••",
                controller: _newPasswordController,
                isObscure: _obscureNew,
                suffixIcon: _obscureNew
                    ? Icons.visibility_off
                    : Icons.visibility,
                suffixPressed: () => setState(() => _obscureNew = !_obscureNew),
                validator: (value) => _validation(
                  value: value,
                  message: "Password baru belum diisi",
                  isNewPassword: true,
                ),
              ),

              SizedBox(height: 2.h),

              CustomTextFormField(
                label: "Konfirmasi Password Baru",
                hint: "••••••••",
                controller: _newPasswordConfirmController,
                isObscure: _obscureConfirm,
                suffixIcon: _obscureConfirm
                    ? Icons.visibility_off
                    : Icons.visibility,
                suffixPressed: () =>
                    setState(() => _obscureConfirm = !_obscureConfirm),
                validator: (value) => _validation(
                  value: value,
                  message: "Konfirmasi password belum diisi",
                  isPasswordConfirm: true,
                ),
              ),

              Align(
                alignment: Alignment.centerRight,
                child: TextButton(
                  onPressed: () {},
                  child: Text(
                    "Lupa password?",
                    style: TextStyle(
                      color: AppColor.primaryColor,
                      fontWeight: FontWeight.bold,
                      fontSize: isTablet
                          ? (AppFontSize.medium - 1.25).sp
                          : (AppFontSize.small - 1.25).sp,
                    ),
                  ),
                ),
              ),

              SizedBox(height: 4.h),

              ElevatedButton(
                onPressed: profileControllerState.isLoading
                    ? null
                    : _updatePassword,
                style: ElevatedButton.styleFrom(
                  backgroundColor: AppColor.primaryColor,
                  minimumSize: Size(double.infinity, 7.h),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(3.w),
                  ),
                  disabledBackgroundColor: Colors.grey.shade300,
                ),
                child: Text(
                  "Perbarui Password",
                  style: TextStyle(
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                    fontSize: AppFontSize.medium.sp,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
