
import 'package:bookmywages/consts_widgets/app_assets.dart';
import 'package:bookmywages/consts_widgets/app_colors.dart';
import 'package:bookmywages/viewmodel/api_controller.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import 'package:fluttertoast/fluttertoast.dart';

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

  @override
  ConsumerState<ProfileChangepass> createState() => _ProfileChangepassState();
}

class _ProfileChangepassState extends ConsumerState<ProfileChangepass> {
  final TextEditingController _newPasswordController = TextEditingController();
  final TextEditingController _confirmPasswordController =
      TextEditingController();
  final _formKey = GlobalKey<FormState>();
  bool _obscureNewPassword = true;
  bool _obscureConfirmPassword = true;
  String? _newPasswordError;
  String? _confirmPasswordError;

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

  Future<void> _submitForm() async {
    FocusScope.of(context).unfocus();

    // Reset errors
    setState(() {
      _newPasswordError = null;
      _confirmPasswordError = null;
    });

    if (_formKey.currentState!.validate()) {
      try {
        final success = await ref.read(
          changepasswordProvider(_newPasswordController.text).future,
        );

        if (success && mounted) {
          Fluttertoast.showToast(
            msg: "Password changed successfully",
            backgroundColor: Colors.green,
            textColor: Colors.white,
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.BOTTOM,
          );
          Navigator.pop(context);
        } else {
          Fluttertoast.showToast(
            msg: "Failed to change password",
            backgroundColor: Colors.red,
            textColor: Colors.white,
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.BOTTOM,
          );
        }
      } catch (e) {
        if (mounted) {
          Fluttertoast.showToast(
            msg: "Error: ${e.toString()}",
            backgroundColor: Colors.red,
            textColor: Colors.white,
            toastLength: Toast.LENGTH_LONG,
            gravity: ToastGravity.BOTTOM,
          );
        }
      }
    }
  }

  String? _validateNewPassword(String? value) {
    if (value == null || value.isEmpty) {
      setState(() {
        _newPasswordError = "Please enter a password";
      });
      return "";
    }
    if (value.length < 6) {
      // Fixed: was 4, should be 6 as per error message
      setState(() {
        _newPasswordError = "Password must be at least 6 characters";
      });
      return "";
    }
    setState(() {
      _newPasswordError = null;
    });
    return null;
  }

  String? _validateConfirmPassword(String? value) {
    if (value == null || value.isEmpty) {
      setState(() {
        _confirmPasswordError = "Please confirm your password";
      });
      return "";
    }
    if (value != _newPasswordController.text) {
      setState(() {
        _confirmPasswordError = "Passwords don't match";
      });
      return "";
    }
    setState(() {
      _confirmPasswordError = null;
    });
    return null;
  }

  @override
  Widget build(BuildContext context) {
    final keyboardHeight = MediaQuery.of(context).viewInsets.bottom;
    final isKeyboardVisible = keyboardHeight > 0;
    final screenHeight = MediaQuery.of(context).size.height;

    return Scaffold(
      backgroundColor: AppColors.secondprimary,
      resizeToAvoidBottomInset: false, // Keep false to prevent white space
      body: GestureDetector(
        onTap: () => FocusScope.of(context).unfocus(),
        child: Container(
          height: screenHeight, // Fixed height
          color: AppColors.secondprimary,
          child: SafeArea(
            child: Column(
              children: [
                // Header with back button
                Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Row(
                    children: [
                      GestureDetector(
                        onTap: () => Navigator.pop(context),
                        child: const Icon(
                          Icons.arrow_back_ios_new,
                          size: 20,
                          color: Colors.black,
                        ),
                      ),
                      const Expanded(
                        child: Center(
                          child: Text(
                            'Change Password',
                            style: TextStyle(
                              fontSize: 20,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ),
                      ),
                      const SizedBox(width: 20),
                    ],
                  ),
                ),

                // Scrollable content with proper height calculation
                Expanded(
                  child: SingleChildScrollView(
                    physics: const ClampingScrollPhysics(),
                    padding: EdgeInsets.only(
                      left: 16.0,
                      right: 16.0,
                      bottom: isKeyboardVisible ? keyboardHeight + 16 : 16.0,
                    ),
                    child: Column(
                      children: [
                        // Show smaller image when keyboard is visible, normal size when not
                        if (!isKeyboardVisible) ...[
                          Image.asset(
                            AppAssets.changepass,
                            width: MediaQuery.of(context).size.width * 0.7,
                            height: MediaQuery.of(context).size.height * 0.3,
                            fit: BoxFit.contain,
                          ),
                          const SizedBox(height: 16),
                        ] else ...[
                          // Smaller image when keyboard is open
                          Image.asset(
                            AppAssets.changepass,
                            width: MediaQuery.of(context).size.width * 0.4,
                            height: screenHeight * 0.12, // Even smaller height
                            fit: BoxFit.contain,
                          ),
                          const SizedBox(height: 8),
                        ],

                        // Form to change password
                        Form(
                          key: _formKey,
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              const Text(
                                "Create Password",
                                style: TextStyle(
                                  fontFamily: 'Gilroy-Bold',
                                  fontSize: 20,
                                  fontWeight: FontWeight.w700,
                                  color: Colors.black87,
                                  height: 18.68 / 20,
                                  letterSpacing: 0.5,
                                ),
                                textAlign: TextAlign.center,
                              ),

                              const SizedBox(height: 20),
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Container(
                                    height: 53,
                                    decoration: BoxDecoration(
                                      color: const Color(0xFFFDFFFF),
                                      borderRadius: BorderRadius.circular(15),
                                      border: Border.all(
                                        color: const Color(0xFF8C8A8A),
                                      ),
                                    ),
                                    child: TextFormField(
                                      controller: _newPasswordController,
                                      obscureText: _obscureNewPassword,
                                      decoration: InputDecoration(
                                        hintText: "Enter new password",
                                        contentPadding:
                                            const EdgeInsets.symmetric(
                                              horizontal: 16,
                                              vertical: 10,
                                            ),
                                        border: InputBorder.none,
                                        hintStyle: const TextStyle(
                                          fontFamily: 'Martel',
                                          fontWeight: FontWeight.w700,
                                          fontSize: 14,
                                          height: 29 / 14,
                                          letterSpacing: -0.5,
                                          color: Color(0xFF757576),
                                        ),
                                        suffixIcon: IconButton(
                                          icon: Icon(
                                            _obscureNewPassword
                                                ? Icons.visibility_off
                                                : Icons.visibility,
                                            color: Colors.grey,
                                          ),
                                          onPressed: () {
                                            setState(() {
                                              _obscureNewPassword =
                                                  !_obscureNewPassword;
                                            });
                                          },
                                        ),
                                      ),
                                      validator: _validateNewPassword,
                                    ),
                                  ),
                                  SizedBox(
                                    height: _newPasswordError != null ? 28 : 0,
                                    child:
                                        _newPasswordError != null
                                            ? Padding(
                                              padding: const EdgeInsets.only(
                                                top: 8.0,
                                                left: 16.0,
                                              ),
                                              child: Text(
                                                _newPasswordError!,
                                                style: const TextStyle(
                                                  color: Colors.red,
                                                  fontSize: 12,
                                                ),
                                              ),
                                            )
                                            : null,
                                  ),
                                ],
                              ),

                              const SizedBox(height: 20),
                              const Text(
                                "Confirm Password",
                                style: TextStyle(
                                  fontFamily: 'Gilroy-Bold',
                                  fontSize: 20,
                                  fontWeight: FontWeight.w700,
                                  color: Colors.black87,
                                  height: 18.68 / 20,
                                  letterSpacing: 0.5,
                                ),
                                textAlign: TextAlign.center,
                              ),

                              const SizedBox(height: 20),
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Container(
                                    height: 53,
                                    decoration: BoxDecoration(
                                      color: const Color(0xFFFDFFFF),
                                      borderRadius: BorderRadius.circular(15),
                                      border: Border.all(
                                        color: const Color(0xFF8C8A8A),
                                      ),
                                    ),
                                    child: TextFormField(
                                      controller: _confirmPasswordController,
                                      obscureText: _obscureConfirmPassword,
                                      decoration: InputDecoration(
                                        hintText: "Confirm your password",
                                        contentPadding:
                                            const EdgeInsets.symmetric(
                                              horizontal: 16,
                                              vertical: 10,
                                            ),
                                        border: InputBorder.none,
                                        hintStyle: const TextStyle(
                                          fontFamily: 'Martel',
                                          fontWeight: FontWeight.w700,
                                          fontSize: 14,
                                          height: 29 / 14,
                                          letterSpacing: -0.5,
                                          color: Color(0xFF757576),
                                        ),
                                        suffixIcon: IconButton(
                                          icon: Icon(
                                            _obscureConfirmPassword
                                                ? Icons.visibility_off
                                                : Icons.visibility,
                                            color: Colors.grey,
                                          ),
                                          onPressed: () {
                                            setState(() {
                                              _obscureConfirmPassword =
                                                  !_obscureConfirmPassword;
                                            });
                                          },
                                        ),
                                      ),
                                      validator: _validateConfirmPassword,
                                    ),
                                  ),
                                  SizedBox(
                                    height:
                                        _confirmPasswordError != null ? 28 : 0,
                                    child:
                                        _confirmPasswordError != null
                                            ? Padding(
                                              padding: const EdgeInsets.only(
                                                top: 8.0,
                                                left: 16.0,
                                              ),
                                              child: Text(
                                                _confirmPasswordError!,
                                                style: const TextStyle(
                                                  color: Colors.red,
                                                  fontSize: 12,
                                                ),
                                              ),
                                            )
                                            : null,
                                  ),
                                ],
                              ),

                              const SizedBox(height: 20),
                              Center(
                                child: SizedBox(
                                  width: 299,
                                  height: 61.71,
                                  child: ElevatedButton(
                                    onPressed: _submitForm,
                                    style: ElevatedButton.styleFrom(
                                      backgroundColor: const Color(0xFF0066FF),
                                      foregroundColor: Colors.white,
                                      shape: RoundedRectangleBorder(
                                        borderRadius: BorderRadius.circular(
                                          34.77,
                                        ),
                                      ),
                                      elevation: 0,
                                    ),
                                    child: const Text(
                                      "Save",
                                      style: TextStyle(
                                        fontFamily: 'Gilroy-Bold',
                                        fontWeight: FontWeight.w700,
                                        fontSize: 28.76,
                                        height: 1.0,
                                        letterSpacing: 0.01,
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                              // Add some bottom spacing
                              SizedBox(height: isKeyboardVisible ? 16 : 30),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
