import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../screens/main_screen.dart';
import '../../domain/models/login_request.dart';
import '../blocs/login/login_bloc.dart';
import '../blocs/login/login_event.dart';
import '../blocs/login/login_state.dart';
import 'onboarding_button.dart';

class AuthForm extends StatefulWidget {
  final VoidCallback? onSubmit;

  const AuthForm({super.key, this.onSubmit});

  @override
  State<AuthForm> createState() => _AuthFormState();
}

class _AuthFormState extends State<AuthForm> {
  bool _obscure = true;

  // Text controllers
  final TextEditingController _phoneNumberController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();

  // Focus nodes for text fields
  late FocusNode _phoneNumberFocusNode;
  late FocusNode _passwordFocusNode;

  void _handleLogin() {
    // Validate inputs
    if (_phoneNumberController.text.trim().isEmpty) {
      _showError('الرجاء إدخال رقم الهاتف');
      return;
    }

    if (_passwordController.text.trim().isEmpty) {
      _showError('الرجاء إدخال كلمة المرور');
      return;
    }

    // Unfocus any focused text field
    _phoneNumberFocusNode.unfocus();
    _passwordFocusNode.unfocus();

    // Dispatch login event
    final request = LoginRequest(
      phoneNumber: _phoneNumberController.text.trim(),
      password: _passwordController.text.trim(),
    );

    context.read<LoginBloc>().add(LoginSubmitted(request));
  }

  void _showError(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.red,
        behavior: SnackBarBehavior.floating,
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    // Initialize focus nodes
    _phoneNumberFocusNode = FocusNode();
    _passwordFocusNode = FocusNode();
  }

  @override
  void dispose() {
    // Clean up controllers and focus nodes
    _phoneNumberController.dispose();
    _passwordController.dispose();
    _phoneNumberFocusNode.dispose();
    _passwordFocusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // Get screen dimensions
    final screenSize = MediaQuery.of(context).size;
    final screenWidth = screenSize.width;
    final screenHeight = screenSize.height;

    // Calculate responsive dimensions
    final formWidth = screenWidth > 600 ? screenWidth * 0.5 : screenWidth * 0.9;
    final formHeight =
        screenHeight > 800 ? screenHeight * 0.6 : screenHeight * 0.8;
    final borderWidth = formWidth + 20;
    final titleFontSize = screenWidth > 600 ? 28.0 : 24.0;
    final labelFontSize = screenWidth > 600 ? 18.0 : 16.0;
    final fieldFontSize = screenWidth > 600 ? 18.0 : 16.0;
    final verticalSpacing = screenHeight > 800 ? 34.0 : 24.0;
    final fieldSpacing = screenHeight > 800 ? 30.0 : 20.0;
    final buttonSpacing = screenHeight > 800 ? 100.0 : 60.0;
    final bottomSpacing = screenHeight > 800 ? 40.0 : 20.0;
    final horizontalPadding = screenWidth > 600 ? 30.0 : 25.0;
    final verticalPadding = screenHeight > 800 ? 38.0 : 28.0;

    return BlocListener<LoginBloc, LoginState>(
      listener: (context, state) {
        if (state is LoginSuccess) {
          // Call the onSubmit callback if provided
          if (widget.onSubmit != null) {
            widget.onSubmit!();
          }

          // Navigate to the MainPage
          Navigator.pushReplacement(
            context,
            MaterialPageRoute(builder: (context) => const MainPage()),
          );
        } else if (state is LoginError) {
          _showError(state.message);
        }
      },
      child: Directionality(
        textDirection: TextDirection.rtl,
        child: FocusScope(
          child: Stack(
            alignment: Alignment.center,
            children: [
              // Border container - decorative element behind the form
              Container(
                width: borderWidth,
                constraints: BoxConstraints(
                  minHeight: formHeight + 40,
                  maxHeight:
                      formHeight + 80, // Allows shrinking when keyboard opens
                ),
                decoration: BoxDecoration(
                  color: Colors.transparent,
                  borderRadius: BorderRadius.circular(32),
                  border: Border.all(color: const Color(0xDD00C28E), width: 1),
                ),
              ),

              // Main form container
              Container(
                width: formWidth,
                padding: EdgeInsets.symmetric(
                  horizontal: horizontalPadding,
                  vertical: verticalPadding,
                ),
                decoration: BoxDecoration(
                  color: const Color(0xFFEEFFFA),
                  borderRadius: BorderRadius.circular(28),
                  boxShadow: const [
                    BoxShadow(
                      color: Colors.black26,
                      blurRadius: 10,
                      offset: Offset(0, 5),
                    ),
                  ],
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    /// Title
                    Center(
                      child: Text(
                        "تسجيل دخول",
                        style: TextStyle(
                          fontSize: titleFontSize,
                          fontWeight: FontWeight.bold,
                          color: Colors.black87,
                        ),
                      ),
                    ),

                    SizedBox(height: verticalSpacing),

                    /// Phone Number Label
                    Align(
                      alignment: Alignment.centerRight,
                      child: Text(
                        "رقم الهاتف",
                        style: TextStyle(
                          fontSize: labelFontSize,
                          color: Colors.black87,
                        ),
                      ),
                    ),
                    const SizedBox(height: 8),

                    _buildField(
                      controller: _phoneNumberController,
                      hint: "رقم الهاتف",
                      obscure: false,
                      keyboardType: TextInputType.phone,
                      focusNode: _phoneNumberFocusNode,
                      textInputAction: TextInputAction.next,
                      onSubmitted: (_) {
                        // Move focus to password field when next is pressed
                        FocusScope.of(context).requestFocus(_passwordFocusNode);
                      },
                      fontSize: fieldFontSize,
                    ),

                    SizedBox(height: fieldSpacing),

                    /// Password Label
                    Align(
                      alignment: Alignment.centerRight,
                      child: Text(
                        "كلمة المرور",
                        style: TextStyle(
                          fontSize: labelFontSize,
                          color: Colors.black87,
                        ),
                      ),
                    ),
                    const SizedBox(height: 8),

                    _buildField(
                      controller: _passwordController,
                      hint: "كلمة المرور",
                      obscure: _obscure,
                      hasEye: true,
                      focusNode: _passwordFocusNode,
                      textInputAction: TextInputAction.done,
                      onSubmitted: (_) => _handleLogin(),
                      fontSize: fieldFontSize,
                    ),

                    SizedBox(height: buttonSpacing), // Responsive spacing

                    BlocBuilder<LoginBloc, LoginState>(
                      builder: (context, state) {
                        final isLoading = state is LoginLoading;
                        return Center(
                          child: OnboardingButton(
                            text:
                                isLoading
                                    ? "جاري تسجيل الدخول..."
                                    : "تسجيل دخول",
                            backgroundColor: const Color.fromARGB(
                              239,
                              35,
                              87,
                              74,
                            ),
                            onPressed: isLoading ? null : _handleLogin,
                          ),
                        );
                      },
                    ),

                    SizedBox(height: bottomSpacing),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildField({
    TextEditingController? controller,
    required String hint,
    required bool obscure,
    bool hasEye = false,
    TextInputType? keyboardType,
    FocusNode? focusNode,
    TextInputAction? textInputAction,
    Function(String)? onSubmitted,
    required double fontSize,
  }) {
    return Container(
      decoration: BoxDecoration(
        color: const Color(0xDEDEDEDE),
        borderRadius: BorderRadius.circular(7),
        boxShadow: const [
          BoxShadow(color: Colors.black26, blurRadius: 6, offset: Offset(0, 2)),
        ],
      ),
      child: TextField(
        controller: controller,
        focusNode: focusNode,
        obscureText: obscure,
        keyboardType: keyboardType,
        textAlign: TextAlign.right,
        textInputAction: textInputAction,
        onSubmitted: onSubmitted,
        style: TextStyle(fontSize: fontSize),
        decoration: InputDecoration(
          hintText: hint,
          hintStyle: const TextStyle(color: Colors.black54),
          border: InputBorder.none,
          contentPadding: const EdgeInsets.symmetric(
            vertical: 16,
            horizontal: 16,
          ),
          suffixIcon:
              hasEye
                  ? IconButton(
                    icon: Icon(
                      obscure ? Icons.visibility_off : Icons.visibility,
                      color: Colors.black54,
                    ),
                    onPressed: () {
                      setState(() => _obscure = !obscure);
                    },
                  )
                  : null,
        ),
      ),
    );
  }
}
