import 'package:cheminova/provider/change_password_provider.dart';
import 'package:cheminova/provider/login_provider.dart';
import 'package:cheminova/screens/password_change_screen.dart';
import 'package:cheminova/widgets/common_app_bar.dart';
import 'package:cheminova/widgets/common_background.dart';
import 'package:cheminova/widgets/common_elevated_button.dart';
import 'package:cheminova/widgets/common_text_form_field.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../widgets/common_drawer.dart';
import 'home_screen.dart';

class ChangePasswordPage extends StatefulWidget {
  const ChangePasswordPage({super.key});

  @override
  State<ChangePasswordPage> createState() => _ChangePasswordPageState();
}

class _ChangePasswordPageState extends State<ChangePasswordPage> {
  late ChangePasswordProvider changePasswordProvider; // Provider to manage state and logic
  final _formKey = GlobalKey<FormState>(); // Form key to manage form validation

  @override
  void initState() {
    changePasswordProvider = ChangePasswordProvider(); // Initialize the provider
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    // Use ChangeNotifierProvider to listen to ChangePasswordProvider updates
    return ChangeNotifierProvider<ChangePasswordProvider>(
        create: (_) => changePasswordProvider,
        builder: (context, child) {
          return Stack( // Stack to manage overlay loading indicator
            children: [
              CommonBackground( // Custom background widget
                isFullWidth: true,
                child: Scaffold(
                    drawer: const CommonDrawer(), // Custom drawer widget
                    backgroundColor: Colors.transparent,
                    appBar: CommonAppBar(
                      title: const Text(''),
                      backgroundColor: Colors.transparent, // Transparent AppBar
                      elevation: 0,
                      actions: [
                        IconButton(
                          onPressed: () {
                            Navigator.pop(context); // Back button action
                          },
                          icon: Image.asset('assets/Back_attendance.png'),
                          padding: const EdgeInsets.only(right: 20),
                        ),
                      ],
                    ),
                    body: SingleChildScrollView( // Scrollable form
                      child: Column(
                        children: [
                          Container(
                            padding: const EdgeInsets.all(20.0).copyWith(top: 15, bottom: 30),
                            margin: const EdgeInsets.symmetric(horizontal: 30.0),
                            decoration: BoxDecoration( // Styling for the form container
                                border: Border.all(color: Colors.white),
                                color: const Color(0xffB4D1E5).withOpacity(0.9),
                                borderRadius: BorderRadius.circular(26.0)),
                            child: Form( // Form widget to validate input fields
                              key: _formKey, // Reference to form state
                              child: Column(
                                mainAxisSize: MainAxisSize.min,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: <Widget>[
                                  const SizedBox(height: 20),
                                  const Text(
                                    'Change Password',
                                    style: TextStyle(
                                      fontSize: 30,
                                      color: Colors.black,
                                      fontWeight: FontWeight.w500,
                                      fontFamily: 'Roboto',
                                    ),
                                  ),
                                  const SizedBox(height: 20),

                                  // Old Password Field
                                  Consumer<ChangePasswordProvider>(
                                    builder: (context, value, child) =>
                                        CommonTextFormField(
                                            controller: value.oldPasswordController, // Old password controller
                                            validator: (val) {
                                              if (val == null || val.isEmpty) {
                                                return 'Please enter your password'; // Validation for empty input
                                              }
                                              return null;
                                            },
                                            title: 'Old Password'),
                                  ),
                                  const SizedBox(height: 20),

                                  // New Password Field
                                  Consumer<ChangePasswordProvider>(
                                    builder: (context, value, child) =>
                                        CommonTextFormField(
                                            controller: value.newPasswordController, // New password controller
                                            validator: (val) {
                                              if (val == null || val.isEmpty) {
                                                return 'Please enter your password'; // Validation for empty input
                                              }
                                              return null;
                                            },
                                            title: 'New Password'),
                                  ),
                                  const SizedBox(height: 20),

                                  // Confirm Password Field
                                  Consumer<ChangePasswordProvider>(
                                    builder: (context, value, child) =>
                                        CommonTextFormField(
                                            controller: value.confirmPasswordController, // Confirm password controller
                                            validator: (val) {
                                              if (val == null || val.isEmpty) {
                                                return 'Please enter your password'; // Validation for empty input
                                              } else if (val !=
                                                  value.newPasswordController.text) {
                                                return 'Password does not match'; // Validation for mismatched password
                                              }
                                              return null;
                                            },
                                            title: 'Confirm Password'),
                                  ),
                                  const SizedBox(height: 15),

                                  // Submit button
                                  Align(
                                    alignment: Alignment.center,
                                    child: Consumer<ChangePasswordProvider>(
                                      builder: (context, value, child) =>
                                          CommonElevatedButton(
                                            backgroundColor: const Color(0xff004791), // Button styling
                                            borderRadius: 30,
                                            width: double.infinity,
                                            height: kToolbarHeight - 10,
                                            text: 'SIGN IN', // Button text
                                            isLoading: false,
                                            onPressed: value.isLoading
                                                ? null
                                                : () async {
                                              if (_formKey.currentState!.validate()) {
                                                // If form is valid, proceed with password change
                                                value.changePassword().then((result) {
                                                  var (status, message) = result;
                                                  ScaffoldMessenger.of(context).showSnackBar(
                                                      SnackBar(content: Text(message))
                                                  ); // Show success or error message
                                                  if (status) {
                                                    // Navigate to HomePage if password change is successful
                                                    Navigator.pushReplacement(
                                                        context,
                                                        MaterialPageRoute(
                                                            builder: (context) =>
                                                            const HomePage()));
                                                  }
                                                });
                                              }
                                            },
                                          ),
                                    ),
                                  )
                                ],
                              ),
                            ),
                          ),
                        ],
                      ),
                    )),
              ),

              // Overlay loading indicator when processing
              Consumer<ChangePasswordProvider>(
                builder: (context, value, child) => value.isLoading
                    ? Container(
                    color: Colors.black.withOpacity(0.5), // Overlay background
                    child: const Center(child: CircularProgressIndicator())) // Show loading indicator
                    : Container(),
              )
            ],
          );
        });
  }
}
