import 'package:citycards_partner_flutter/constants/app_assets.dart';
import 'package:citycards_partner_flutter/constants/app_colors.dart';
import 'package:citycards_partner_flutter/core/app_router.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_fonts/google_fonts.dart';
import '../../custome_widgets/custom_button.dart';
import '../../custome_widgets/custom_textfield.dart';
import '../blocs/forgot_password/forgot_password_bloc.dart';

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

  @override
  State<ForgotPasswordPage> createState() => _ForgotPasswordPageState();
}

class _ForgotPasswordPageState extends State<ForgotPasswordPage> {
  final _emailController = TextEditingController();
  final _emailFocusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    // Reset the form state when entering the page
    context.read<ForgotPasswordBloc>().add(ForgotPasswordReset());
  }

  @override
  void dispose() {
    _emailController.dispose();
    _emailFocusNode.dispose();
    super.dispose();
  }

  bool _isEmailValid(String email) {
    return RegExp(
            r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$')
        .hasMatch(email);
  }

  void _onSendLinkPressed(BuildContext context) {
    FocusManager.instance.primaryFocus?.unfocus();

    final email = _emailController.text.trim();
    final isEmailValid = _isEmailValid(email);

    context.read<ForgotPasswordBloc>().add(ForgotPasswordEmailErrorToggled(!isEmailValid));

    if (isEmailValid) {
      context.read<ForgotPasswordBloc>().add(
        ForgotPasswordSubmitted(emailAddress: email),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
      behavior: HitTestBehavior.translucent,
      child: Scaffold(
        backgroundColor: AppColors.backgroundWhite,
        body: BlocConsumer<ForgotPasswordBloc, ForgotPasswordState>(
          listener: (context, state) {
            if (state.status == ForgotPasswordStatus.success) {
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(
                  content: Text("OTP sent successfully!"),
                  backgroundColor: AppColors.successGreen,
                ),
              );
              Navigator.pushNamed(
                context,
                AppRouter.otpVerification,
                arguments: _emailController.text.trim(),
              );
            } else if (state.status == ForgotPasswordStatus.failure) {
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(
                  content: Text(state.errorMessage ?? "An error occurred"),
                  backgroundColor: Colors.redAccent,
                ),
              );
            }
          },
          builder: (context, state) {
            final isLoading = state.status == ForgotPasswordStatus.loading;

            return SafeArea(
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: 24.w),
                child: Column(
                  children: [
                    Expanded(
                      child: SingleChildScrollView(
                        child: Column(
                          children: [
                            SizedBox(height: 40.h),
                            // ===== LOGO SECTION =====
                            Center(
                              child: Column(
                                children: [
                                  Image.asset(
                                    AppAssets.appIcon,
                                    height: 60.h,
                                  ),
                                  SizedBox(height: 8.h),
                                  Text(
                                    "Partner's App",
                                    style: GoogleFonts.poppins(
                                      color: AppColors.primaryRed,
                                      fontSize: 20.sp,
                                      fontWeight: FontWeight.w500,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            SizedBox(height: 60.h),

                            // ===== HEADER TEXT =====
                            Text(
                              "Change Your Password",
                              textAlign: TextAlign.center,
                              style: GoogleFonts.poppins(
                                color: AppColors.black,
                                fontSize: 24.sp,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                            SizedBox(height: 12.h),
                            Text(
                              "Enter your email to update your password and secure your account",
                              textAlign: TextAlign.center,
                              style: GoogleFonts.poppins(
                                color: AppColors.textGrey,
                                fontSize: 15.sp,
                                height: 1.4,
                              ),
                            ),
                            SizedBox(height: 48.h),

                            // ===== EMAIL FIELD =====
                            CustomTextField(
                              label: 'Email Address',
                              hintText: 'you@example.com',
                              controller: _emailController,
                              focusNode: _emailFocusNode,
                              prefixIcon: Icons.email_outlined,
                              hasError: state.showEmailError,
                              errorText: 'Please enter a valid email address',
                              keyboardType: TextInputType.emailAddress,
                              textInputAction: TextInputAction.done,
                              readOnly: isLoading,
                              onChanged: (val) {
                                // Only validate and update error if user has attempted submission
                                if (state.showEmailError) {
                                  context.read<ForgotPasswordBloc>().add(
                                    ForgotPasswordEmailErrorToggled(!_isEmailValid(val.trim())),
                                  );
                                }
                              },
                              onSubmitted: (_) => _onSendLinkPressed(context),
                            ),
                            SizedBox(height: 20.h),
                          ],
                        ),
                      ),
                    ),
                    SizedBox(height: 20.h),
                    // ===== SEND LINK BUTTON =====
                    CustomButton(
                      text: "Send OTP",
                      isLoading: isLoading,
                      onPressed: () => _onSendLinkPressed(context),
                    ),
                    SizedBox(height: 24.h),
                  ],
                ),
              ),
            );
          },
        ),
      ),
    );
  }
}