// screens/login_screen.dart
import 'package:flutter/material.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
import 'package:tugas_akhir_supabase/services/session_manager.dart';
import 'package:tugas_akhir_supabase/services/auth_services.dart';
import 'package:get_it/get_it.dart';
import 'dart:async';

// Define theme colors
const Color primaryColor = Color(0xFF056839);
const Color secondaryColor = Color(0xFF4CAF50);
const Color backgroundColor = Color(0xFFF5F5F5);
const Color surfaceColor = Colors.white;
const Color textColor = Color(0xFF2D3748);
const Color subtextColor = Color(0xFF718096);

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

  @override
  _LoginScreenState createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  final _formKey = GlobalKey<FormState>();
  final _emailController = TextEditingController();
  final _passwordController = TextEditingController();
  final _focusPassword = FocusNode();
  bool _isLoading = false;
  bool _obscurePassword = true;
  late final AuthServices _authServices;

  @override
  void initState() {
    super.initState();
    _authServices = GetIt.instance<AuthServices>();
  }

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

  // Safe method to show snackbars that won't crash if context is invalid
  void _safeShowSnackBar(String message, {Color backgroundColor = Colors.red}) {
    if (!mounted) return;
    
    // Get the ScaffoldMessenger reference once and early
    final scaffoldMessenger = ScaffoldMessenger.of(context);
    
    // Now use the reference instead of accessing context again
    scaffoldMessenger.showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: backgroundColor,
        behavior: SnackBarBehavior.floating,
      ),
    );
  }

  Future<void> _login() async {
    if (!_formKey.currentState!.validate()) return;

    // Dismiss keyboard
    FocusScope.of(context).unfocus();
    
    setState(() => _isLoading = true);

    try {
      // Tambahkan timeout tambahan untuk keamanan
      final loginFuture = _authServices.signInWithEmailPassword(
        _emailController.text.trim(),
        _passwordController.text.trim(),
      );
      
      // Tambahkan timeout tambahan di tingkat UI
      final response = await loginFuture.timeout(
        const Duration(seconds: 20),
        onTimeout: () {
          throw TimeoutException('Koneksi timeout. Silakan coba lagi nanti.');
        },
      );
      
      if (!mounted) return;
      
      // Check if user's email is confirmed
      if (response.user != null && response.session != null) {
        // Initialize session
        await SessionManager.initializeSession();
        
        // Navigate to home screen
        Navigator.pushReplacementNamed(context, '/home');
      } else {
        // This should not happen normally, but handle it just in case
        _safeShowSnackBar(
          'Login berhasil, namun terjadi masalah saat memulai sesi Anda. Silakan coba lagi atau hubungi dukungan jika masalah berlanjut.',
          backgroundColor: Colors.orange
        );
      }
    } on TimeoutException catch (e) {
      if (!mounted) return;
      _safeShowSnackBar('Waktu login habis. Periksa koneksi internet Anda dan coba lagi.');
    } on AuthException catch (e) {
      if (!mounted) return;
      
      String errorMessage = 'Email atau password salah';
      
      // Handle specific error cases
      if (e.message.toLowerCase().contains('invalid_credentials') ||
          e.message.toLowerCase().contains('invalid_grant')) {
        errorMessage = 'Email atau password salah';
      } else if (e.message.toLowerCase().contains('email') && 
                (e.message.toLowerCase().contains('confirm') || 
                 e.message.toLowerCase().contains('verified'))) {
        errorMessage = 'Email belum diverifikasi. Silakan cek email Anda.';
      } else if (e.message.toLowerCase().contains('rate_limit')) {
        errorMessage = 'Terlalu banyak percobaan. Silakan tunggu beberapa saat.';
      }
      
      _safeShowSnackBar(errorMessage);
    } catch (e) {
      if (!mounted) return;
      _safeShowSnackBar('Gagal masuk. Terjadi kesalahan yang tidak terduga. Mohon coba lagi nanti.');
    } finally {
      if (mounted) {
        setState(() => _isLoading = false);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: backgroundColor,
      body: SafeArea(
        child: SingleChildScrollView(
          physics: const AlwaysScrollableScrollPhysics(),
          child: Padding(
            padding: const EdgeInsets.all(24.0),
            child: Form(
              key: _formKey,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  const SizedBox(height: 40),
                  // Logo and Welcome Text
                  Center(
                    child: Container(
                      width: 100,
                      height: 100,
                      decoration: BoxDecoration(
                        color: primaryColor.withOpacity(0.1),
                        shape: BoxShape.circle,
                      ),
                      child: const Icon(
                        Icons.eco,
                        size: 60,
                        color: primaryColor,
                      ),
                    ),
                  ),
                  const SizedBox(height: 24),
                  Text(
                    'Selamat Datang',
                    textAlign: TextAlign.center,
                    style: Theme.of(context).textTheme.headlineMedium?.copyWith(
                      color: primaryColor,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 8),
                  Text(
                    'Masuk untuk Melanjutkan Aplikasi TaniSM4RT',
                    textAlign: TextAlign.center,
                    style: Theme.of(context).textTheme.bodyLarge?.copyWith(
                      color: subtextColor,
                    ),
                  ),
                  const SizedBox(height: 40),

                  // Email Field - Simplified
                  TextFormField(
                    controller: _emailController,
                    keyboardType: TextInputType.emailAddress,
                    textInputAction: TextInputAction.next,
                    onFieldSubmitted: (_) {
                      FocusScope.of(context).requestFocus(_focusPassword);
                    },
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return 'Masukkan email';
                      }
                      if (!value.contains('@')) {
                        return 'Masukkan alamat email yang valid';
                      }
                      return null;
                    },
                    decoration: InputDecoration(
                      labelText: 'Email',
                      hintText: 'Masukkan email',
                      prefixIcon: const Icon(Icons.email_outlined, color: primaryColor),
                      border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
                    ),
                  ),
                  const SizedBox(height: 20),

                  // Password Field - Simplified
                  TextFormField(
                    controller: _passwordController,
                    focusNode: _focusPassword,
                    obscureText: _obscurePassword,
                    textInputAction: TextInputAction.done,
                    onFieldSubmitted: (_) => _login(),
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return 'Masukkan kata sandi';
                      }
                      if (value.length < 6) {
                        return 'Kata sandi minimal 6 karakter';
                      }
                      return null;
                    },
                    decoration: InputDecoration(
                      labelText: 'Password',
                      hintText: 'Masukkan password',
                      prefixIcon: const Icon(Icons.lock_outline, color: primaryColor),
                      suffixIcon: IconButton(
                        icon: Icon(
                          _obscurePassword ? Icons.visibility_off : Icons.visibility,
                          color: subtextColor,
                        ),
                        onPressed: () {
                          setState(() {
                            _obscurePassword = !_obscurePassword;
                          });
                        },
                      ),
                      border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
                    ),
                  ),
                  const SizedBox(height: 24),

                  // Forgot Password Link
                  Align(
                    alignment: Alignment.centerRight,
                    child: TextButton(
                      onPressed: () {
                        Navigator.pushNamed(context, '/forgot-password');
                      },
                      style: TextButton.styleFrom(
                        foregroundColor: primaryColor,
                      ),
                      child: const Text('Lupa Password?', style: TextStyle(fontWeight: FontWeight.w600)),
                    ),
                  ),
                  const SizedBox(height: 8),

                  // Login Button - Simplified
                  ElevatedButton(
                    onPressed: _isLoading ? null : _login,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: primaryColor,
                      foregroundColor: Colors.white,
                      padding: const EdgeInsets.symmetric(vertical: 16),
                      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
                    ),
                    child: _isLoading
                        ? const SizedBox(
                            height: 20,
                            width: 20,
                            child: CircularProgressIndicator(
                              strokeWidth: 2,
                              valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                            ),
                          )
                        : const Text('Masuk', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
                  ),
                  const SizedBox(height: 16),

                  // Register Link
                  TextButton(
                    onPressed: () => Navigator.pushNamed(context, '/register'),
                    style: TextButton.styleFrom(foregroundColor: primaryColor),
                    child: RichText(
                      textAlign: TextAlign.center,
                      text: TextSpan(
                        text: "Belum punya akun? ",
                        style: TextStyle(color: subtextColor),
                        children: const [
                          TextSpan(
                            text: 'Daftar',
                            style: TextStyle(color: primaryColor, fontWeight: FontWeight.bold),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
