import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../core/theme/app_colors.dart';
import '../../core/theme/app_typography.dart';
import '../../services/app_provider.dart';
import '../../services/api_service.dart';
import '../../widgets/gradient_mesh.dart';
import '../../widgets/glass_card.dart';

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

  @override
  State<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  final _emailCtrl = TextEditingController();
  final _passCtrl = TextEditingController();
  final _emailFocus = FocusNode();
  final _passFocus = FocusNode();
  bool _loading = false;
  String? _error;
  bool _obscure = true;
  String? _lastUsedEmail;
  bool _showLastUsedHint = false;

  @override
  void initState() {
    super.initState();
    final auth = context.read<AppProvider>().auth;
    _lastUsedEmail = auth.lastUsedEmail;
    if (_lastUsedEmail != null && _lastUsedEmail!.isNotEmpty) {
      _showLastUsedHint = true;
    }
  }

  void _useLastEmail() {
    if (_lastUsedEmail != null) {
      _emailCtrl.text = _lastUsedEmail!;
      setState(() => _showLastUsedHint = false);
      _passFocus.requestFocus();
    }
  }

  Future<void> _login() async {
    final email = _emailCtrl.text.trim();
    final pass = _passCtrl.text;

    if (email.isEmpty && pass.isEmpty) {
      setState(() => _error = 'Enter your email and password');
      return;
    }
    if (email.isEmpty) {
      setState(() => _error = 'Enter your email address');
      return;
    }
    if (!RegExp(r'^[\w\.\-]+@[\w\.\-]+\.\w{2,}$').hasMatch(email)) {
      setState(() => _error = 'Please enter a valid email address');
      return;
    }
    if (pass.isEmpty) {
      setState(() => _error = 'Enter your password');
      return;
    }
    setState(() { _loading = true; _error = null; });
    try {
      final provider = context.read<AppProvider>();
      await provider.auth.login(email, pass);
      if (!mounted) return;
      Navigator.of(context).pushReplacementNamed('/home');
    } on ApiException catch (e) {
      final msg = e.message.toLowerCase();
      if (msg.contains('credential') || msg.contains('password') || msg.contains('invalid')) {
        setState(() => _error = 'Incorrect email or password. Please try again.');
      } else if (msg.contains('not found') || msg.contains('no account')) {
        setState(() => _error = 'No account found with this email. Sign up instead?');
      } else {
        setState(() => _error = e.message);
      }
    } catch (e) {
      setState(() => _error = 'Connection error. Check your internet and try again.');
    } finally {
      if (mounted) setState(() => _loading = false);
    }
  }

  @override
  void dispose() {
    _emailCtrl.dispose();
    _passCtrl.dispose();
    _emailFocus.dispose();
    _passFocus.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.navy,
      body: Stack(
        children: [
          const Positioned.fill(child: GradientMesh()),
          SafeArea(
            child: Center(
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(24),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Container(
                      width: 80,
                      height: 80,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        boxShadow: [
                          BoxShadow(color: AppColors.royalBlue.withValues(alpha: 0.3), blurRadius: 30),
                        ],
                      ),
                      child: ClipOval(
                        child: Image.asset('assets/icon/reasonabledoubt-icon.png', fit: BoxFit.cover),
                      ),
                    ),
                    const SizedBox(height: 24),
                    Text('Welcome Back', style: AppTypography.displayLg.copyWith(color: Colors.white)),
                    const SizedBox(height: 8),
                    Text('Sign in to your legal assistant', style: AppTypography.bodyMd.copyWith(color: AppColors.textSecondary)),
                    const SizedBox(height: 32),

                    // Last used email suggestion
                    if (_showLastUsedHint && _lastUsedEmail != null)
                      Padding(
                        padding: const EdgeInsets.only(bottom: 16),
                        child: GestureDetector(
                          onTap: _useLastEmail,
                          child: GlassCard(
                            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                            child: Row(
                              children: [
                                Container(
                                  width: 36, height: 36,
                                  decoration: BoxDecoration(
                                    shape: BoxShape.circle,
                                    color: AppColors.royalBlue.withValues(alpha: 0.15),
                                  ),
                                  child: const Icon(Icons.person_rounded, color: AppColors.royalBlue, size: 18),
                                ),
                                const SizedBox(width: 12),
                                Expanded(
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Text('Last signed in as', style: AppTypography.bodySm.copyWith(color: AppColors.textMuted, fontSize: 11)),
                                      Text(_lastUsedEmail!, style: AppTypography.bodyMd.copyWith(color: Colors.white, fontWeight: FontWeight.w500)),
                                    ],
                                  ),
                                ),
                                Container(
                                  padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
                                  decoration: BoxDecoration(
                                    color: AppColors.royalBlue.withValues(alpha: 0.2),
                                    borderRadius: BorderRadius.circular(8),
                                  ),
                                  child: Text('Use', style: AppTypography.bodySm.copyWith(color: AppColors.royalBlue, fontWeight: FontWeight.w600)),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),

                    GlassCard(
                      padding: const EdgeInsets.all(24),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.stretch,
                        children: [
                          // Email field
                          Text('Email Address', style: AppTypography.bodySm.copyWith(color: AppColors.textMuted, fontWeight: FontWeight.w500)),
                          const SizedBox(height: 6),
                          Container(
                            decoration: BoxDecoration(
                              color: AppColors.glassSurface,
                              borderRadius: BorderRadius.circular(14),
                              border: Border.all(color: AppColors.glassBorder),
                            ),
                            child: TextField(
                              controller: _emailCtrl,
                              focusNode: _emailFocus,
                              keyboardType: TextInputType.emailAddress,
                              textInputAction: TextInputAction.next,
                              onSubmitted: (_) => _passFocus.requestFocus(),
                              style: AppTypography.bodyMd.copyWith(color: Colors.white),
                              decoration: InputDecoration(
                                hintText: 'your.email@example.com',
                                hintStyle: AppTypography.bodyMd.copyWith(color: AppColors.textMuted.withValues(alpha: 0.5)),
                                prefixIcon: const Icon(Icons.email_rounded, color: AppColors.textMuted, size: 20),
                                border: InputBorder.none,
                                contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
                              ),
                            ),
                          ),
                          const SizedBox(height: 16),

                          // Password field
                          Text('Password', style: AppTypography.bodySm.copyWith(color: AppColors.textMuted, fontWeight: FontWeight.w500)),
                          const SizedBox(height: 6),
                          Container(
                            decoration: BoxDecoration(
                              color: AppColors.glassSurface,
                              borderRadius: BorderRadius.circular(14),
                              border: Border.all(color: AppColors.glassBorder),
                            ),
                            child: TextField(
                              controller: _passCtrl,
                              focusNode: _passFocus,
                              obscureText: _obscure,
                              textInputAction: TextInputAction.done,
                              onSubmitted: (_) => _login(),
                              style: AppTypography.bodyMd.copyWith(color: Colors.white),
                              decoration: InputDecoration(
                                hintText: 'Enter your password',
                                hintStyle: AppTypography.bodyMd.copyWith(color: AppColors.textMuted.withValues(alpha: 0.5)),
                                prefixIcon: const Icon(Icons.lock_rounded, color: AppColors.textMuted, size: 20),
                                suffixIcon: IconButton(
                                  icon: Icon(_obscure ? Icons.visibility_off_rounded : Icons.visibility_rounded, color: AppColors.textMuted, size: 20),
                                  onPressed: () => setState(() => _obscure = !_obscure),
                                ),
                                border: InputBorder.none,
                                contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
                              ),
                            ),
                          ),

                          // Forgot password
                          Align(
                            alignment: Alignment.centerRight,
                            child: TextButton(
                              onPressed: () {
                                final email = _emailCtrl.text.trim();
                                if (email.isEmpty) {
                                  ScaffoldMessenger.of(context).showSnackBar(
                                    SnackBar(
                                      content: const Text('Enter your email first, then tap Forgot Password'),
                                      backgroundColor: AppColors.glassSurface,
                                      behavior: SnackBarBehavior.floating,
                                      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                                    ),
                                  );
                                  return;
                                }
                                context.read<AppProvider>().api.passwordResetRequest(email).then((_) {
                                  if (!mounted) return;
                                  ScaffoldMessenger.of(context).showSnackBar(
                                    SnackBar(
                                      content: Text('Password reset link sent to $email'),
                                      backgroundColor: AppColors.success,
                                      behavior: SnackBarBehavior.floating,
                                      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                                    ),
                                  );
                                }).catchError((_) {
                                  if (!mounted) return;
                                  ScaffoldMessenger.of(context).showSnackBar(
                                    SnackBar(
                                      content: const Text('Could not send reset email. Please try again.'),
                                      backgroundColor: AppColors.error,
                                      behavior: SnackBarBehavior.floating,
                                      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                                    ),
                                  );
                                });
                              },
                              style: TextButton.styleFrom(padding: const EdgeInsets.symmetric(vertical: 4)),
                              child: Text('Forgot Password?', style: AppTypography.bodySm.copyWith(color: AppColors.royalBlue)),
                            ),
                          ),

                          // Error
                          if (_error != null) ...[
                            Container(
                              padding: const EdgeInsets.all(10),
                              decoration: BoxDecoration(
                                color: AppColors.error.withValues(alpha: 0.1),
                                borderRadius: BorderRadius.circular(10),
                              ),
                              child: Row(
                                children: [
                                  const Icon(Icons.error_outline_rounded, color: AppColors.error, size: 16),
                                  const SizedBox(width: 8),
                                  Expanded(child: Text(_error!, style: AppTypography.bodySm.copyWith(color: AppColors.error))),
                                ],
                              ),
                            ),
                            const SizedBox(height: 12),
                          ],

                          const SizedBox(height: 8),
                          // Sign in button
                          GestureDetector(
                            onTap: _loading ? null : _login,
                            child: AnimatedContainer(
                              duration: const Duration(milliseconds: 200),
                              height: 52,
                              decoration: BoxDecoration(
                                gradient: LinearGradient(colors: [AppColors.royalBlue, AppColors.royalBlue.withValues(alpha: 0.8)]),
                                borderRadius: BorderRadius.circular(14),
                                boxShadow: [BoxShadow(color: AppColors.royalBlue.withValues(alpha: 0.4), blurRadius: 20, offset: const Offset(0, 6))],
                              ),
                              child: Center(
                                child: _loading
                                    ? const SizedBox(width: 22, height: 22, child: CircularProgressIndicator(color: Colors.white, strokeWidth: 2.5))
                                    : Text('Sign In', style: AppTypography.button.copyWith(color: Colors.white)),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    const SizedBox(height: 24),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text("Don't have an account? ", style: AppTypography.bodyMd.copyWith(color: AppColors.textMuted)),
                        GestureDetector(
                          onTap: () => Navigator.of(context).pushReplacementNamed('/register'),
                          child: Text('Sign Up', style: AppTypography.button.copyWith(color: AppColors.royalBlue)),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
