import 'package:cheminova/provider/login_provider.dart';
import 'package:cheminova/screens/forgot_password_screen.dart';
import 'package:cheminova/screens/verify_phone_screen.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 'home_screen.dart';

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

  @override
  State<LoginPage> createState() => _LoginPageState(); // Create state for LoginPage
}

class _LoginPageState extends State<LoginPage> {
  late LoginProvider loginProvider; // Declare LoginProvider
  final _formKey = GlobalKey<FormState>(); // Global key for form validation

  @override
  void initState() {
    loginProvider = LoginProvider(); // Initialize LoginProvider
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<LoginProvider>( // Provide LoginProvider to the widget tree
      create: (_) => loginProvider,
      builder: (context, child) => Scaffold(
          body: CommonBackground(
            isFullWidth: false,
            child: Center(
              child: SingleChildScrollView( // Allow scrolling for the content
                child: Column(
                  children: [
                    const Text('Welcome',
                        style: TextStyle(
                            fontSize: 24,
                            fontWeight: FontWeight.w400,
                            color: Colors.white,
                            fontFamily: 'Roboto')),
                    const SizedBox(height: 50), // Spacer
                    Align(
                      alignment: Alignment.center,
                      child: Container(
                        decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(12)), // Styling for logo container
                        padding: const EdgeInsets.all(8),
                        child: Image.asset('assets/cheminova_logo.png', height: kToolbarHeight - 25), // Display logo
                      ),
                    ),
                    const SizedBox(height: 60), // Spacer
                    Container(
                      padding: const EdgeInsets.all(20.0).copyWith(top: 15, bottom: 30), // Padding for login form
                      margin: const EdgeInsets.symmetric(horizontal: 30.0).copyWith(bottom: 50), // Margin for login form
                      decoration: BoxDecoration(
                          border: Border.all(color: Colors.white),
                          color: const Color(0xffB4D1E5).withOpacity(0.9),
                          borderRadius: BorderRadius.circular(26.0)), // Styling for form container
                      child: Form(
                        key: _formKey, // Assign global key for form validation
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: <Widget>[
                            const SizedBox(height: 20), // Spacer
                            const Text('Login',
                                style: TextStyle(
                                    fontSize: 30,
                                    color: Colors.black,
                                    fontWeight: FontWeight.w500,
                                    fontFamily: 'Roboto')),
                            const Text('Sign in to continue',
                                style: TextStyle(
                                    fontSize: 14,
                                    color: Colors.black,
                                    fontWeight: FontWeight.w300,
                                    fontFamily: 'Roboto')),
                            const SizedBox(height: 20), // Spacer
                            Consumer<LoginProvider>( // Listen for changes in LoginProvider
                                builder: (context, value, child) =>
                                    CommonTextFormField(
                                        controller: value.emailController, // Email input field
                                        validator: (value) {
                                          if (value == null || value.isEmpty) {
                                            return 'Please enter your email id'; // Validation message
                                          }
                                          if (!RegExp(r'^[^@\s]+@[^@\s]+\.[^@\s]+$')
                                              .hasMatch(value)) {
                                            return 'Please enter a valid email id'; // Validation message for invalid email
                                          }
                                          return null;
                                        },
                                        title: 'Username')), // Field title
                            const SizedBox(height: 20), // Spacer
                            Consumer<LoginProvider>( // Listen for changes in LoginProvider
                                builder: (context, value, child) =>
                                    CommonTextFormField(
                                        obscureText: true, // Hide password input
                                        controller: value.passwordController, // Password input field
                                        validator: (value) {
                                          if (value == null || value.isEmpty) {
                                            return 'Please enter your password'; // Validation message
                                          }
                                          return null;
                                        },
                                        title: 'Password')), // Field title
                            const SizedBox(height: 15), // Spacer

                            Align(
                              alignment: Alignment.center,
                              child: TextButton( // Button for forgot password
                                onPressed: () {
                                  Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                          builder: (context) =>
                                          const ForgotPasswordScreen())); // Navigate to forgot password screen
                                },
                                child: const Text('Forgot Password?',
                                    style: TextStyle(
                                        fontSize: 20,
                                        color: Colors.black,
                                        fontWeight: FontWeight.w400,
                                        fontFamily: 'Roboto')),
                              ),
                            ),
                            const SizedBox(height: 15), // Spacer
                            Align(
                                alignment: Alignment.center,
                                child: Consumer<LoginProvider>( // Listen for changes in LoginProvider
                                  builder: (context, value, child) =>
                                      CommonElevatedButton(
                                        backgroundColor: const Color(0xff004791), // Button color
                                        borderRadius: 30,
                                        width: double.infinity, // Full width button
                                        height: kToolbarHeight - 10,
                                        text: 'SIGN IN', // Button text
                                        isLoading: value.isLoading, // Show loading indicator if true
                                        onPressed: value.isLoading // Disable button if loading
                                            ? null
                                            : () async {
                                          if (_formKey.currentState!.validate()) { // Validate the form
                                            value.login().then((result) { // Call login method
                                              var (status, message) = result; // Destructure result
                                              ScaffoldMessenger.of(context)
                                                  .showSnackBar(SnackBar(
                                                  content: Text(message))); // Show message in snackbar
                                              if (status) {
                                                Navigator.pushReplacement(
                                                    context,
                                                    MaterialPageRoute(
                                                        builder: (context) =>
                                                        const HomePage())); // Navigate to home screen if successful
                                              }
                                            });
                                          }
                                        },
                                      ),
                                )),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          )),
    );
  }
}
