import 'dart:math' as math;

import 'package:base_project/core/constants/ui_constants.dart';
import 'package:base_project/core/providers/dynamic_theme_provider.dart';
import 'package:base_project/core/providers/theme_provider.dart';
import 'package:base_project/shared/widgets/inputs/modern_text_field.dart';
import 'package:base_project/view_model/auth/auth_view_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

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

  @override
  State<GetOtpView> createState() => _GetOtpViewState();
}

class _GetOtpViewState extends State<GetOtpView> with TickerProviderStateMixin {
  final TextEditingController _emailController = TextEditingController();
  final FocusNode _emailFocusNode = FocusNode();

  late AnimationController _pageAnimationController;
  late AnimationController _formAnimationController;
  late AnimationController _particleAnimationController;
  late AnimationController _buttonPulseController;

  late Animation<double> _pageFadeAnimation;
  late Animation<Offset> _pageSlideAnimation;
  late Animation<double> _formScaleAnimation;
  late Animation<double> _particleRotationAnimation;
  late Animation<double> _buttonPulseAnimation;

  bool _isEmailFocused = false;
  bool _isEmailValid = false;
  List<String> _emailHistory = [];
  List<String> _filteredSuggestions = [];

  @override
  void initState() {
    super.initState();
    _initializeAnimations();
    _setupFocusListeners();
    _loadEmailHistory();
  }

  void _initializeAnimations() {
    _pageAnimationController = AnimationController(
      duration: const Duration(milliseconds: 1200),
      vsync: this,
    );

    _formAnimationController = AnimationController(
      duration: const Duration(milliseconds: 800),
      vsync: this,
    );

    _particleAnimationController = AnimationController(
      duration: const Duration(seconds: 20),
      vsync: this,
    );

    _buttonPulseController = AnimationController(
      duration: const Duration(milliseconds: 1500),
      vsync: this,
    );

    _pageFadeAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _pageAnimationController,
      curve: Curves.easeInOut,
    ));

    _pageSlideAnimation = Tween<Offset>(
      begin: const Offset(0, 0.3),
      end: Offset.zero,
    ).animate(CurvedAnimation(
      parent: _pageAnimationController,
      curve: Curves.easeOutCubic,
    ));

    _formScaleAnimation = Tween<double>(
      begin: 0.8,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _formAnimationController,
      curve: Curves.elasticOut,
    ));

    _particleRotationAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _particleAnimationController,
      curve: Curves.linear,
    ));

    _buttonPulseAnimation = Tween<double>(
      begin: 1.0,
      end: 1.05,
    ).animate(CurvedAnimation(
      parent: _buttonPulseController,
      curve: Curves.easeInOut,
    ));

    _startAnimations();
  }

  void _startAnimations() {
    _pageAnimationController.forward();
    Future.delayed(const Duration(milliseconds: 400), () {
      _formAnimationController.forward();
    });
    _particleAnimationController.repeat();

    // Start button pulse animation when email is valid
    _startButtonPulseAnimation();
  }

  void _startButtonPulseAnimation() {
    if (_isEmailValid) {
      _buttonPulseController.repeat(reverse: true);
    }
  }

  void _setupFocusListeners() {
    _emailFocusNode.addListener(() {
      setState(() {
        _isEmailFocused = _emailFocusNode.hasFocus;
      });
    });

    _emailController.addListener(() {
      final wasValid = _isEmailValid;
      final emailText = _emailController.text.trim();

      // Better email validation regex that supports + in email
      final emailRegex =
          RegExp(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$');
      final isValid = emailText.isNotEmpty && emailRegex.hasMatch(emailText);

      print("Email validation - Text: '$emailText', Valid: $isValid");

      setState(() {
        _isEmailValid = isValid;
        _filteredSuggestions = _getFilteredSuggestions(emailText);
      });

      // Control button pulse animation
      if (_isEmailValid && !wasValid) {
        _buttonPulseController.repeat(reverse: true);
      } else if (!_isEmailValid && wasValid) {
        _buttonPulseController.stop();
        _buttonPulseController.reset();
      }
    });
  }

  Future<void> _loadEmailHistory() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final list = prefs.getStringList('email_history') ?? [];
      setState(() {
        _emailHistory = list;
        _filteredSuggestions =
            _getFilteredSuggestions(_emailController.text.trim());
      });
    } catch (_) {}
  }

  Future<void> _saveEmailToHistory(String email) async {
    if (email.isEmpty) return;
    final normalized = email.trim().toLowerCase();
    final set = {..._emailHistory.map((e) => e.toLowerCase())};
    if (set.contains(normalized)) return;
    final updated = [email, ..._emailHistory];
    try {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setStringList('email_history', updated);
    } catch (_) {}
    setState(() {
      _emailHistory = updated;
      _filteredSuggestions =
          _getFilteredSuggestions(_emailController.text.trim());
    });
  }

  List<String> _getFilteredSuggestions(String query) {
    if (query.isEmpty) return _emailHistory.take(5).toList();
    final lower = query.toLowerCase();
    final results =
        _emailHistory.where((e) => e.toLowerCase().contains(lower)).toList();
    // Keep most recent first; limit to 5
    return results.take(5).toList();
  }

  @override
  void dispose() {
    _pageAnimationController.dispose();
    _formAnimationController.dispose();
    _particleAnimationController.dispose();
    _buttonPulseController.dispose();
    _emailController.dispose();
    _emailFocusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;

    return Consumer<DynamicThemeProvider>(
      builder: (context, dynamicThemeProvider, child) {
        final colorScheme = dynamicThemeProvider.getCurrentColorScheme(
            Theme.of(context).brightness == Brightness.dark);

        return Scaffold(
          body: Container(
            width: double.infinity,
            height: double.infinity,
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [
                  colorScheme.primary,
                  colorScheme.primary.withOpacity(0.8),
                  colorScheme.secondary.withOpacity(0.6),
                ],
                stops: const [0.0, 0.6, 1.0],
              ),
            ),
            child: Stack(
              children: [
                // Animated Background Particles
                _buildParticleBackground(colorScheme),

                // Glassmorphism Background
                _buildGlassmorphismBackground(colorScheme),

                // Main Content
                SafeArea(
                  child: SingleChildScrollView(
                    padding: UIConstants.getResponsivePadding(
                      context,
                      mobile: const EdgeInsets.all(UIConstants.spacing16),
                      tablet: const EdgeInsets.all(UIConstants.spacing24),
                      desktop: const EdgeInsets.all(UIConstants.spacing32),
                    ),
                    child: ConstrainedBox(
                      constraints: BoxConstraints(
                        minHeight: size.height -
                            MediaQuery.of(context).padding.top -
                            MediaQuery.of(context).padding.bottom,
                      ),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          // Back Button & Header
                          _buildHeader(colorScheme),

                          SizedBox(
                              height: UIConstants.getResponsiveSpacing(
                            context,
                            mobile: UIConstants.spacing32,
                            tablet: UIConstants.spacing40,
                            desktop: UIConstants.spacing48,
                          )),

                          // Logo Section
                          _buildLogoSection(colorScheme),

                          SizedBox(
                              height: UIConstants.getResponsiveSpacing(
                            context,
                            mobile: UIConstants.spacing32,
                            tablet: UIConstants.spacing40,
                            desktop: UIConstants.spacing48,
                          )),

                          // Welcome Section
                          _buildWelcomeSection(colorScheme),

                          SizedBox(
                              height: UIConstants.getResponsiveSpacing(
                            context,
                            mobile: UIConstants.spacing32,
                            tablet: UIConstants.spacing40,
                            desktop: UIConstants.spacing48,
                          )),

                          // OTP Form
                          _buildOtpForm(colorScheme),

                          SizedBox(
                              height: UIConstants.getResponsiveSpacing(
                            context,
                            mobile: UIConstants.spacing32,
                            tablet: UIConstants.spacing40,
                            desktop: UIConstants.spacing48,
                          )),

                          // Send OTP Button
                          _buildSendOtpButton(colorScheme),

                          // Email Validation Status
                          SizedBox(height: UIConstants.spacing12),
                          _buildEmailValidationStatus(colorScheme),

                          SizedBox(
                              height: UIConstants.getResponsiveSpacing(
                            context,
                            mobile: UIConstants.spacing24,
                            tablet: UIConstants.spacing32,
                            desktop: UIConstants.spacing40,
                          )),

                          // Back to Login
                          _buildBackToLoginSection(colorScheme),
                        ],
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildHeader(ColorScheme colorScheme) {
    return AnimatedBuilder(
      animation: _pageAnimationController,
      builder: (context, child) {
        return FadeTransition(
          opacity: _pageFadeAnimation,
          child: Row(
            children: [
              Container(
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.2),
                  borderRadius: BorderRadius.circular(UIConstants.radius16),
                  border: Border.all(
                    color: Colors.white.withOpacity(0.3),
                    width: 1,
                  ),
                ),
                child: IconButton(
                  onPressed: () => Navigator.pop(context),
                  icon: Icon(
                    Icons.arrow_back_ios_new,
                    color: Colors.white,
                    size: UIConstants.iconSizeMedium,
                  ),
                  style: IconButton.styleFrom(
                    backgroundColor: Colors.transparent,
                    elevation: 0,
                  ),
                ),
              ),
              const Spacer(),
              Consumer<ThemeProvider>(
                builder: (context, themeProvider, child) {
                  return Container(
                    decoration: BoxDecoration(
                      color: Colors.white.withOpacity(0.2),
                      borderRadius: BorderRadius.circular(UIConstants.radius16),
                      border: Border.all(
                        color: Colors.white.withOpacity(0.3),
                        width: 1,
                      ),
                    ),
                    child: IconButton(
                      onPressed: () => themeProvider.toggleTheme(),
                      icon: Icon(
                        themeProvider.isDarkMode
                            ? Icons.light_mode
                            : Icons.dark_mode,
                        color: Colors.white,
                        size: UIConstants.iconSizeMedium,
                      ),
                      style: IconButton.styleFrom(
                        backgroundColor: Colors.transparent,
                        elevation: 0,
                      ),
                    ),
                  );
                },
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildLogoSection(ColorScheme colorScheme) {
    return AnimatedBuilder(
      animation: _pageAnimationController,
      builder: (context, child) {
        return FadeTransition(
          opacity: _pageFadeAnimation,
          child: SlideTransition(
            position: _pageSlideAnimation,
            child: Container(
              width: UIConstants.getResponsiveValue(
                context,
                mobile: UIConstants.logoSizeLarge,
                tablet: UIConstants.logoSizeXLarge,
                desktop: UIConstants.logoSizeXLarge * 1.2,
              ),
              height: UIConstants.getResponsiveValue(
                context,
                mobile: UIConstants.logoSizeLarge,
                tablet: UIConstants.logoSizeXLarge,
                desktop: UIConstants.logoSizeXLarge * 1.2,
              ),
              decoration: BoxDecoration(
                color: Colors.white.withOpacity(0.95),
                borderRadius: BorderRadius.circular(UIConstants.radius24),
                border: Border.all(
                  color: Colors.white.withOpacity(0.3),
                  width: 2,
                ),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.2),
                    blurRadius: 30,
                    offset: const Offset(0, 15),
                    spreadRadius: 10,
                  ),
                ],
              ),
              child: Icon(
                Icons.verified_user_outlined,
                size: UIConstants.getResponsiveValue(
                  context,
                  mobile: UIConstants.iconSizeXLarge,
                  tablet: UIConstants.iconSizeXLarge * 1.2,
                  desktop: UIConstants.iconSizeXLarge * 1.5,
                ),
                color: colorScheme.primary,
              ),
            ),
          ),
        );
      },
    );
  }

  Widget _buildWelcomeSection(ColorScheme colorScheme) {
    return AnimatedBuilder(
      animation: _pageAnimationController,
      builder: (context, child) {
        return FadeTransition(
          opacity: _pageFadeAnimation,
          child: SlideTransition(
            position: _pageSlideAnimation,
            child: Container(
              padding: UIConstants.cardPaddingMedium,
              decoration: BoxDecoration(
                color: Colors.white.withOpacity(0.95),
                borderRadius: BorderRadius.circular(UIConstants.radius20),
                border: Border.all(
                  color: Colors.white.withOpacity(0.3),
                  width: 1,
                ),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.1),
                    blurRadius: 20,
                    offset: const Offset(0, 10),
                    spreadRadius: 5,
                  ),
                ],
              ),
              child: Column(
                children: [
                  Text(
                    'Get OTP',
                    style: Theme.of(context).textTheme.headlineMedium?.copyWith(
                          color: colorScheme.primary,
                          fontWeight: FontWeight.w700,
                          letterSpacing: 0.5,
                        ),
                    textAlign: TextAlign.center,
                  ),
                  const SizedBox(height: UIConstants.spacing12),
                  Text(
                    'Enter your email to receive a one-time password',
                    style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                          color: colorScheme.onSurface.withOpacity(0.8),
                          fontWeight: FontWeight.w400,
                        ),
                    textAlign: TextAlign.center,
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  Widget _buildOtpForm(ColorScheme colorScheme) {
    return AnimatedBuilder(
      animation: _formAnimationController,
      builder: (context, child) {
        return Transform.scale(
          scale: _formScaleAnimation.value,
          child: Container(
            width: UIConstants.getResponsiveValue(
              context,
              mobile: double.infinity,
              tablet: 450,
              desktop: 500,
            ),
            padding: UIConstants.cardPaddingLarge,
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.95),
              borderRadius: BorderRadius.circular(UIConstants.radius24),
              border: Border.all(
                color: Colors.white.withOpacity(0.3),
                width: 1,
              ),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.15),
                  blurRadius: 25,
                  offset: const Offset(0, 15),
                  spreadRadius: 8,
                ),
              ],
            ),
            child: Column(
              children: [
                // Email Field
                _buildEnhancedTextField(
                  label: 'Email Address',
                  hint: 'Enter your email address',
                  controller: _emailController,
                  focusNode: _emailFocusNode,
                  keyboardType: TextInputType.emailAddress,
                  prefixIcon: Icons.email_outlined,
                  isFocused: _isEmailFocused,
                  colorScheme: colorScheme,
                  textInputAction: TextInputAction.done,
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return 'Email is required';
                    }
                    if (!RegExp(
                            r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$')
                        .hasMatch(value)) {
                      return 'Please enter a valid email';
                    }
                    return null;
                  },
                ),
                if (_filteredSuggestions.isNotEmpty &&
                    (_isEmailFocused || _emailController.text.isNotEmpty))
                  const SizedBox(height: UIConstants.spacing8),
                if (_filteredSuggestions.isNotEmpty &&
                    (_isEmailFocused || _emailController.text.isNotEmpty))
                  _buildEmailSuggestions(colorScheme),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildEnhancedTextField({
    required String label,
    required String hint,
    required TextEditingController controller,
    required FocusNode focusNode,
    required IconData prefixIcon,
    required bool isFocused,
    required ColorScheme colorScheme,
    bool obscureText = false,
    Widget? suffixIcon,
    TextInputType? keyboardType,
    TextInputAction? textInputAction,
    Function(String)? onSubmitted,
    String? Function(String?)? validator,
  }) {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(UIConstants.radius16),
        border: Border.all(
          color: isFocused ? colorScheme.primary : Colors.grey.withOpacity(0.3),
          width: isFocused ? 2 : 1,
        ),
        boxShadow: isFocused
            ? [
                BoxShadow(
                  color: colorScheme.primary.withOpacity(0.2),
                  blurRadius: 12,
                  spreadRadius: 3,
                ),
              ]
            : null,
      ),
      child: ModernTextField(
        label: label,
        hint: hint,
        controller: controller,
        focusNode: focusNode,
        obscureText: obscureText,
        keyboardType: keyboardType,
        prefixIcon: Icon(
          prefixIcon,
          color: isFocused ? colorScheme.primary : Colors.grey.withOpacity(0.7),
        ),
        suffixIcon: suffixIcon,
        textInputAction: textInputAction,
        onSubmitted: onSubmitted,
        validator: validator,
      ),
    );
  }

  Widget _buildSendOtpButton(ColorScheme colorScheme) {
    return AnimatedBuilder(
      animation: _formAnimationController,
      builder: (context, child) {
        return FadeTransition(
          opacity: _formScaleAnimation,
          child: Consumer<AuthViewModel>(
            builder: (context, provider, child) {
              return Container(
                width: UIConstants.getResponsiveValue(
                  context,
                  mobile: double.infinity,
                  tablet: 450,
                  desktop: 500,
                ),
                child: _buildEnhancedSendOtpButton(
                  colorScheme: colorScheme,
                  provider: provider,
                  isEmailValid: _isEmailValid,
                ),
              );
            },
          ),
        );
      },
    );
  }

  Widget _buildEnhancedSendOtpButton({
    required ColorScheme colorScheme,
    required AuthViewModel provider,
    required bool isEmailValid,
  }) {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(UIConstants.radius20),
        boxShadow: [
          BoxShadow(
            color: colorScheme.primary.withOpacity(0.3),
            blurRadius: 20,
            offset: const Offset(0, 10),
            spreadRadius: 5,
          ),
        ],
      ),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          onTap: _isEmailValid && !provider.isLoading
              ? () {
                  print(
                      "Button tapped! Email valid: $_isEmailValid, Loading: ${provider.isLoading}");
                  _handleSendOtp(provider);
                }
              : null,
          borderRadius: BorderRadius.circular(UIConstants.radius20),
          splashColor: Colors.white.withOpacity(0.3),
          highlightColor: Colors.white.withOpacity(0.1),
          child: AnimatedContainer(
            duration: const Duration(milliseconds: 300),
            curve: Curves.easeInOut,
            height: UIConstants.buttonHeightLarge,
            // Ensure proper touch target
            constraints: BoxConstraints(
              minHeight: 48.0, // Material Design minimum touch target
            ),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: isEmailValid && !provider.isLoading
                    ? [
                        colorScheme.primary,
                        colorScheme.primary.withOpacity(0.8),
                        colorScheme.secondary.withOpacity(0.7),
                      ]
                    : [
                        Colors.grey.withOpacity(0.3),
                        Colors.grey.withOpacity(0.2),
                      ],
                stops: isEmailValid && !provider.isLoading
                    ? const [0.0, 0.7, 1.0]
                    : const [0.0, 1.0],
              ),
              borderRadius: BorderRadius.circular(UIConstants.radius20),
              border: Border.all(
                color: isEmailValid && !provider.isLoading
                    ? colorScheme.primary.withOpacity(0.3)
                    : Colors.grey.withOpacity(0.2),
                width: 1.5,
              ),
              boxShadow: isEmailValid && !provider.isLoading
                  ? [
                      BoxShadow(
                        color: colorScheme.primary.withOpacity(0.4),
                        blurRadius: 15,
                        offset: const Offset(0, 8),
                        spreadRadius: 3,
                      ),
                    ]
                  : null,
            ),
            child: AnimatedBuilder(
              animation: _buttonPulseController,
              builder: (context, child) {
                return Transform.scale(
                  scale: isEmailValid && !provider.isLoading
                      ? _buttonPulseAnimation.value
                      : 1.0,
                  child: Stack(
                    children: [
                      // Background Animation
                      if (isEmailValid && !provider.isLoading)
                        _buildButtonBackgroundAnimation(colorScheme),

                      // Content
                      Center(
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            // Loading Indicator or Icon
                            if (provider.isLoading) ...[
                              _buildLoadingIndicator(colorScheme),
                              const SizedBox(width: UIConstants.spacing16),
                            ] else ...[
                              _buildButtonIcon(colorScheme),
                              const SizedBox(width: UIConstants.spacing16),
                            ],

                            // Button Text
                            _buildButtonText(colorScheme, provider.isLoading),

                            // Button State Indicator
                            if (!_isEmailValid)
                              Positioned(
                                right: 16,
                                child: Container(
                                  padding: const EdgeInsets.all(4),
                                  decoration: BoxDecoration(
                                    color: Colors.red.withOpacity(0.2),
                                    borderRadius: BorderRadius.circular(12),
                                  ),
                                  child: Icon(
                                    Icons.lock_outline,
                                    color: Colors.red,
                                    size: 16,
                                  ),
                                ),
                              ),
                          ],
                        ),
                      ),

                      // Ripple Effect
                      if (isEmailValid && !provider.isLoading)
                        _buildRippleEffect(colorScheme),
                    ],
                  ),
                );
              },
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildButtonBackgroundAnimation(ColorScheme colorScheme) {
    return AnimatedBuilder(
      animation: _particleAnimationController,
      builder: (context, child) {
        return CustomPaint(
          painter: ButtonBackgroundPainter(
            colorScheme: colorScheme,
            animation: _particleRotationAnimation,
          ),
          size: Size.infinite,
        );
      },
    );
  }

  Widget _buildLoadingIndicator(ColorScheme colorScheme) {
    return SizedBox(
      width: 24,
      height: 24,
      child: CircularProgressIndicator(
        strokeWidth: 2.5,
        valueColor: AlwaysStoppedAnimation<Color>(
          Colors.white.withOpacity(0.9),
        ),
        backgroundColor: Colors.white.withOpacity(0.2),
      ),
    );
  }

  Widget _buildButtonIcon(ColorScheme colorScheme) {
    return AnimatedContainer(
      duration: const Duration(milliseconds: 300),
      child: Icon(
        Icons.send_rounded,
        color: Colors.white.withOpacity(0.95),
        size: UIConstants.iconSizeMedium,
      ),
    );
  }

  Widget _buildButtonText(ColorScheme colorScheme, bool isLoading) {
    return AnimatedDefaultTextStyle(
      duration: const Duration(milliseconds: 300),
      style: Theme.of(context).textTheme.titleMedium?.copyWith(
                color: Colors.white.withOpacity(0.95),
                fontWeight: FontWeight.w700,
                fontSize: 18,
                letterSpacing: 0.5,
              ) ??
          const TextStyle(),
      child: Text(
        isLoading ? 'Sending OTP...' : 'Send OTP',
      ),
    );
  }

  Widget _buildRippleEffect(ColorScheme colorScheme) {
    return Positioned.fill(
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(UIConstants.radius20),
          gradient: RadialGradient(
            center: Alignment.center,
            radius: 0.8,
            colors: [
              Colors.white.withOpacity(0.1),
              Colors.transparent,
            ],
          ),
        ),
      ),
    );
  }

  void _handleSendOtp(AuthViewModel provider) {
    print("_handleSendOtp called!");
    print("Email valid: $_isEmailValid");
    print("Provider loading: ${provider.isLoading}");
    print("Email text: ${_emailController.text}");

    if (_isEmailValid && !provider.isLoading) {
      // Add haptic feedback
      HapticFeedback.lightImpact();

      // Send OTP request
      final data = {'email': _emailController.text.trim().toString()};
      print("Sending OTP request with data: $data");
      provider.getOtp(context, data);
      _saveEmailToHistory(data['email'] as String);
    } else {
      print(
          "Cannot send OTP - Email valid: $_isEmailValid, Loading: ${provider.isLoading}");
    }
  }

  Widget _buildBackToLoginSection(ColorScheme colorScheme) {
    return AnimatedBuilder(
      animation: _formAnimationController,
      builder: (context, child) {
        return FadeTransition(
          opacity: _formScaleAnimation,
          child: Container(
            padding: UIConstants.cardPaddingMedium,
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.9),
              borderRadius: BorderRadius.circular(UIConstants.radius20),
              border: Border.all(
                color: Colors.white.withOpacity(0.3),
                width: 1,
              ),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.1),
                  blurRadius: 15,
                  offset: const Offset(0, 8),
                  spreadRadius: 3,
                ),
              ],
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  "Already have an account? ",
                  style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                        color: Colors.grey.shade700,
                        fontWeight: FontWeight.w500,
                      ),
                ),
                TextButton(
                  onPressed: () => Navigator.pop(context),
                  child: Text(
                    'Back to Login',
                    style: Theme.of(context).textTheme.labelLarge?.copyWith(
                          color: colorScheme.primary,
                          fontWeight: FontWeight.w700,
                          fontSize: 16,
                        ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildParticleBackground(ColorScheme colorScheme) {
    return AnimatedBuilder(
      animation: _particleAnimationController,
      builder: (context, child) {
        return CustomPaint(
          painter: ParticlePainter(
            colorScheme: colorScheme,
            animation: _particleRotationAnimation,
          ),
          size: Size.infinite,
        );
      },
    );
  }

  Widget _buildGlassmorphismBackground(ColorScheme colorScheme) {
    return Positioned.fill(
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white.withOpacity(0.05),
          borderRadius: BorderRadius.circular(UIConstants.radius32),
        ),
      ),
    );
  }

  Widget _buildEmailValidationStatus(ColorScheme colorScheme) {
    // High-contrast pill beneath the field
    final bg = _emailController.text.isEmpty
        ? Colors.white
        : (_isEmailValid ? const Color(0xFFE6F4EA) : const Color(0xFFFFE8E6));
    final fg = _emailController.text.isEmpty
        ? Colors.grey.shade700
        : (_isEmailValid ? const Color(0xFF0F9D58) : const Color(0xFFDB4437));
    final icon = _emailController.text.isEmpty
        ? Icons.info_outline
        : (_isEmailValid ? Icons.check_circle : Icons.error_outline);
    final msg = _emailController.text.isEmpty
        ? 'Enter your email address'
        : (_isEmailValid ? 'Email looks good' : 'Invalid email address');

    return Container(
      width: UIConstants.getResponsiveValue(
        context,
        mobile: double.infinity,
        tablet: 450,
        desktop: 500,
      ),
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
      decoration: BoxDecoration(
        color: bg,
        borderRadius: BorderRadius.circular(UIConstants.radius12),
        border: Border.all(color: fg.withOpacity(0.25), width: 1),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.max,
        children: [
          Icon(icon, color: fg, size: 18),
          const SizedBox(width: 10),
          Expanded(
            child: Text(
              msg,
              style: TextStyle(
                color: fg,
                fontSize: 13,
                fontWeight: FontWeight.w600,
                letterSpacing: 0.2,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildEmailSuggestions(ColorScheme colorScheme) {
    return Container(
      width: UIConstants.getResponsiveValue(
        context,
        mobile: double.infinity,
        tablet: 450,
        desktop: 500,
      ),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(UIConstants.radius12),
        border: Border.all(color: Colors.black.withOpacity(0.08), width: 1),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.06),
            blurRadius: 12,
            offset: const Offset(0, 6),
          ),
        ],
      ),
      child: ListView.separated(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        itemCount: _filteredSuggestions.length,
        separatorBuilder: (_, __) =>
            Divider(height: 1, color: Colors.black.withOpacity(0.06)),
        itemBuilder: (context, index) {
          final suggestion = _filteredSuggestions[index];
          return InkWell(
            onTap: () {
              _emailController.text = suggestion;
              _emailController.selection = TextSelection.fromPosition(
                TextPosition(offset: _emailController.text.length),
              );
              setState(() {
                _filteredSuggestions = [];
              });
            },
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
              child: Row(
                children: [
                  Icon(Icons.history, size: 18, color: Colors.grey.shade600),
                  const SizedBox(width: 10),
                  Expanded(
                    child: Text(
                      suggestion,
                      style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                            color: Colors.grey.shade800,
                            fontWeight: FontWeight.w600,
                          ),
                    ),
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }
}

class ParticlePainter extends CustomPainter {
  final ColorScheme colorScheme;
  final Animation<double> animation;

  ParticlePainter({
    required this.colorScheme,
    required this.animation,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Colors.white.withOpacity(0.1)
      ..style = PaintingStyle.fill;

    final center = Offset(size.width / 2, size.height / 2);
    final radius = size.width * 0.4;

    // Draw rotating particles
    for (int i = 0; i < 8; i++) {
      final angle = (i * 45 + animation.value * 360) * (3.14159 / 180);
      final x = center.dx + radius * math.cos(angle);
      final y = center.dy + radius * math.sin(angle);

      canvas.drawCircle(
        Offset(x, y),
        8 + i * 2,
        paint,
      );
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}

class ButtonBackgroundPainter extends CustomPainter {
  final ColorScheme colorScheme;
  final Animation<double> animation;

  ButtonBackgroundPainter({
    required this.colorScheme,
    required this.animation,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final center = Offset(size.width / 2, size.height / 2);
    final radius = math.min(size.width, size.height) * 0.3;

    // Animated background particles
    final paint = Paint()
      ..color = Colors.white.withOpacity(0.1)
      ..style = PaintingStyle.fill;

    // Draw floating particles
    for (int i = 0; i < 6; i++) {
      final angle = (i * 60 + animation.value * 180) * (3.14159 / 180);
      final x = center.dx + radius * math.cos(angle);
      final y = center.dy + radius * math.sin(angle);

      canvas.drawCircle(
        Offset(x, y),
        4 + i * 1.5,
        paint,
      );
    }

    // Subtle wave effect
    final wavePaint = Paint()
      ..color = Colors.white.withOpacity(0.05)
      ..style = PaintingStyle.stroke
      ..strokeWidth = 1;

    for (int i = 0; i < 3; i++) {
      final waveRadius = radius * (0.5 + i * 0.2) + animation.value * 10;
      canvas.drawCircle(center, waveRadius, wavePaint);
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}
