import 'package:english_learning/features/auth/provider/user_provider.dart';
import 'package:english_learning/features/auth/provider/validator_provider.dart';
import 'package:english_learning/features/auth/screens/forgot_password/forgot_password_screen.dart';
import 'package:english_learning/features/auth/screens/signup/signup_screen.dart';
import 'package:english_learning/features/home/screens/home_screen.dart';
import 'package:english_learning/core/widgets/form_field/custom_field_widget.dart';
import 'package:english_learning/core/widgets/global_button.dart';
import 'package:english_learning/core/utils/styles/theme.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:provider/provider.dart';

class SigninScreen extends StatelessWidget {
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();

  SigninScreen({super.key});

  @override
  Widget build(BuildContext context) {
    final userProvider = Provider.of<UserProvider>(context, listen: false);
    Provider.of<ValidatorProvider>(context, listen: false);

    return Scaffold(
      backgroundColor: AppColors.whiteColor,
      body: Center(
        child: Container(
          margin: const EdgeInsets.symmetric(horizontal: 16),
          child: SingleChildScrollView(
            child: Consumer<ValidatorProvider>(
              builder: (context, validatorProvider, child) {
                return Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const SizedBox(height: 32),
                    Text(
                      'Welcome Back!',
                      style: AppTextStyles.blueTextStyle.copyWith(
                        fontSize: 30,
                        fontWeight: FontWeight.w900,
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      'Login to continue your personalized learning journey.',
                      style: AppTextStyles.greyTextStyle.copyWith(
                        fontSize: 14,
                      ),
                    ),
                    const SizedBox(height: 26),
                    Center(
                      child: SvgPicture.asset(
                        'lib/features/auth/assets/images/login_illustration.svg',
                        width: 200,
                      ),
                    ),
                    const SizedBox(height: 30),
                    CustomFieldWidget(
                      fieldName: 'email',
                      controller: _emailController,
                      isRequired: true,
                      textInputAction: TextInputAction.next,
                      labelText: 'Email Address',
                      hintText: 'Enter Your Email Address',
                      keyboardType: TextInputType.emailAddress,
                      validator: validatorProvider.emailValidator,
                      onChanged: (value) {
                        validatorProvider.validateField(
                          'email',
                          value,
                          validator: validatorProvider.emailValidator,
                        );
                      },
                      errorText: validatorProvider.getError('email'),
                    ),
                    const SizedBox(height: 14),
                    CustomFieldWidget(
                      fieldName: 'password',
                      controller: _passwordController,
                      isRequired: true,
                      textInputAction: TextInputAction.next,
                      labelText: 'Password',
                      hintText: 'Create a Strong Password',
                      obscureText: validatorProvider.isObscure('password'),
                      keyboardType: TextInputType.visiblePassword,
                      validator: validatorProvider.passwordValidator,
                      onChanged: (value) {
                        validatorProvider.validateField(
                          'password',
                          value,
                          validator: validatorProvider.passwordValidator,
                        );
                      },
                      onSuffixIconTap: () =>
                          validatorProvider.toggleVisibility('password'),
                      errorText: validatorProvider.getError('password'),
                    ),
                    const SizedBox(height: 24),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        GestureDetector(
                          onTap: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) =>
                                      const ForgotPasswordScreen()),
                            );
                          },
                          child: ShaderMask(
                            shaderCallback: (bounds) =>
                                AppColors.gradientTheme.createShader(
                              Rect.fromLTWH(0, 0, bounds.width, bounds.height),
                            ),
                            child: const Text(
                              'Forgot Password?',
                              style: TextStyle(
                                fontSize: 13,
                                fontWeight: FontWeight.bold,
                                color: Colors.white,
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 24),
                    GlobalButton(
                      text: 'Login',
                      isLoading: userProvider.isLoading,
                      onPressed: userProvider.isLoading
                          ? null
                          : () async {
                              // Validate email and password fields
                              validatorProvider.validateField(
                                'email',
                                _emailController.text,
                                validator: validatorProvider.emailValidator,
                              );
                              validatorProvider.validateField(
                                'password',
                                _passwordController.text,
                                validator: validatorProvider.passwordValidator,
                              );

                              // If no errors, proceed with login
                              if (validatorProvider.getError('email') == null &&
                                  validatorProvider.getError('password') ==
                                      null) {
                                final isSuccess = await userProvider.login(
                                  email: _emailController.text,
                                  password: _passwordController.text,
                                );

                                if (isSuccess) {
                                  // Navigate to HomeScreen after successful login
                                  Navigator.pushAndRemoveUntil(
                                    context,
                                    MaterialPageRoute(
                                        builder: (context) =>
                                            const HomeScreen()),
                                    (Route<dynamic> route) =>
                                        false, // Remove all previous routes
                                  ).then((_) {
                                    // Reset the fields after login
                                    validatorProvider.resetFields();
                                    _emailController.clear();
                                    _passwordController.clear();
                                  });
                                } else {
                                  // Show error message
                                  ScaffoldMessenger.of(context).showSnackBar(
                                    const SnackBar(
                                      content: Text(
                                          'Login failed, please check your credentials'),
                                      backgroundColor: Colors.red,
                                    ),
                                  );
                                }
                              }
                            },
                    ),
                    const SizedBox(height: 8),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text(
                          'Haven\'t joined us yet? ',
                          style: AppTextStyles.blackTextStyle
                              .copyWith(fontSize: 14),
                        ),
                        GestureDetector(
                          onTap: () {
                            context.read<ValidatorProvider>().resetFields();
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) => SignupScreen()),
                            );
                          },
                          child: Text(
                            'Sign Up Here',
                            style: AppTextStyles.blueTextStyle.copyWith(
                              fontSize: 14,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ],
                );
              },
            ),
          ),
        ),
      ),
    );
  }
}
