// lib/features/auth/reconnection_screen.dart

import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; 
import 'package:http/http.dart' as http; 

import '../../../core/models/user.dart';
import '../../../core/services/database_service.dart';
import '../../../core/networks/api_client.dart';
import '../admin/screens/admin_home_screen.dart';

// --- STRICT COLOR PALETTE MAINTAINED ---
const Color _darkGreen = Color.fromARGB(255, 2, 105, 48);
const Color _standardGold = Color.fromARGB(255, 204, 117, 4);

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

  @override
  State<ReconnectionScreen> createState() => _ReconnectionScreenState();
}

class _ReconnectionScreenState extends State<ReconnectionScreen> with TickerProviderStateMixin {
  bool _isInitializing = true; 
  bool _isLoading = false;     
  
  // 🚀 NEW: State variables to hold in-card messages
  String? _statusMessage;
  Color? _statusColor;

  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  bool _isPasswordVisible = false;

  late AnimationController _animController;
  late Animation<double> _fadeAnimation;
  late Animation<Offset> _slideAnimation;
  late AnimationController _spinController;

  @override
  void initState() {
    super.initState();
    
    _animController = AnimationController(vsync: this, duration: const Duration(milliseconds: 900));
    _fadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(CurvedAnimation(parent: _animController, curve: Curves.easeOut));
    _slideAnimation = Tween<Offset>(begin: const Offset(0, 0.05), end: Offset.zero).animate(CurvedAnimation(parent: _animController, curve: Curves.easeOutCubic));

    _spinController = AnimationController(vsync: this, duration: const Duration(milliseconds: 1200))..repeat();

    Future.delayed(const Duration(milliseconds: 2000), () {
      if (mounted) {
        setState(() {
          _isInitializing = false; 
        });
        _animController.forward(); 
      }
    });
  }

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

  // 🚀 NEW: Replaces the SnackBar with an in-card status update
  void _setStatus(String message, Color color) {
    if (mounted) {
      setState(() {
        _statusMessage = message;
        _statusColor = color;
      });
    }
  }

  String _serverErrorMessage(http.Response response) {
    String detail = '';
    try {
      final decoded = jsonDecode(response.body);
      if (decoded is Map) {
        for (final key in ['detail', 'message', 'error']) {
          final value = decoded[key];
          if (value != null && value.toString().trim().isNotEmpty) {
            detail = value.toString().trim();
            break;
          }
        }
      }
    } on FormatException {
      // HTML/PHP warning pages are common when the server has an API error.
      // Do not put the raw page (which may expose server internals) in the UI.
    }

    final lowerDetail = detail.toLowerCase();
    final exposesServerInternals = [
      'sqlstate',
      'pdoexception',
      'pg_hba.conf',
      'database connection failed',
      'syntax error',
      'stack trace',
    ].any(lowerDetail.contains);

    if (response.statusCode == 401) {
      return 'The server rejected the sign-in (HTTP 401). Check the email and password.';
    }
    if (response.statusCode == 403) {
      return 'This account is not allowed to sign in to the administration portal (HTTP 403).';
    }
    if (response.statusCode == 404) {
      return 'The login API was not found (HTTP 404). Check that the API files and PHP routes are deployed.';
    }
    if (response.statusCode >= 500 || exposesServerInternals) {
      return 'The login server failed (HTTP ${response.statusCode}). Ask the administrator to check the PHP/API and database logs.';
    }
    if (detail.isNotEmpty && !detail.startsWith('<')) {
      final conciseDetail = detail.length > 180
          ? '${detail.substring(0, 180)}…'
          : detail;
      return 'Sign-in failed (HTTP ${response.statusCode}): $conciseDetail';
    }
    return 'Sign-in failed with HTTP ${response.statusCode}. Check the login API response.';
  }

  String _exceptionMessage(Object error) {
    if (error is TimeoutException) {
      return 'The login request timed out. The server took too long to respond.';
    }
    if (error is http.ClientException) {
      final detail = error.message.replaceAll(RegExp(r'\s+'), ' ').trim();
      final diagnostic = detail.length > 150
          ? '${detail.substring(0, 150)}…'
          : detail;
      return diagnostic.isEmpty
          ? 'The app could not reach the login API. Check the API URL, internet connection, and hosting availability.'
          : 'Could not reach the login API: $diagnostic';
    }
    final errorType = error.runtimeType.toString();
    if (errorType.contains('SocketException')) {
      final diagnostic = error.toString().replaceAll(RegExp(r'\s+'), ' ').trim();
      final concise = diagnostic.length > 150
          ? '${diagnostic.substring(0, 150)}…'
          : diagnostic;
      return 'Could not connect to the login server: $concise';
    }
    if (errorType.contains('HandshakeException')) {
      final diagnostic = error.toString().replaceAll(RegExp(r'\s+'), ' ').trim();
      final concise = diagnostic.length > 150
          ? '${diagnostic.substring(0, 150)}…'
          : diagnostic;
      return 'Secure connection failed: $concise';
    }
    if (error is FormatException) {
      return 'The login API returned an invalid response. Check for PHP errors or non-JSON output on the server.';
    }
    return 'Sign-in failed inside the app (${error.runtimeType}). Please try again; if it continues, share the login error from the app log with the administrator.';
  }

  Future<void> _loginAndContinue() async {
    final email = _emailController.text.trim();
    String password = _passwordController.text;

    // Clear any previous errors
    setState(() => _statusMessage = null);

    if (email.isEmpty || password.isEmpty) {
      _setStatus('Please enter your credentials.', _standardGold);
      return;
    }

    if (password.length > 72) {
      password = password.substring(0, 72);
    }

    setState(() => _isLoading = true);
    
    try {
      // Login is public. Discard any prior session before authenticating again.
      ApiClient.bearerToken = null;
      await DatabaseService.clearToken();
      final headers = {'Content-Type': 'application/json'};
      final body = jsonEncode({'email': email, 'password': password});
      final String backendUrl = ApiClient.baseUrl; 

      // 1. ATTEMPT ADMIN LOGIN FIRST (Updated for PHP routing)
      final adminResponse = await http.post(
        Uri.parse('$backendUrl/api/admin.php/login'), 
        headers: headers, 
        body: body
      ).timeout(const Duration(seconds: 15));
      http.Response response = adminResponse;

      // 2. IF ADMIN FAILS, ATTEMPT STAFF/USER LOGIN (Updated for PHP routing)
      if (response.statusCode != 200) {
        final userResponse = await http.post(
          Uri.parse('$backendUrl/api/users.php/login'), 
          headers: headers, 
          body: body
        ).timeout(const Duration(seconds: 15));
        // Keep a server/configuration error visible instead of hiding it behind
        // the second endpoint's ordinary invalid-credentials response.
        response = userResponse.statusCode == 200 ||
                (adminResponse.statusCode < 500 && adminResponse.statusCode != 404)
            ? userResponse
            : adminResponse;
      }

      if (!mounted) return;

      if (response.statusCode == 200) {
        final decoded = jsonDecode(response.body);
        if (decoded is! Map) {
          throw const FormatException('Login response must be a JSON object.');
        }
        final Map<String, dynamic> responseBody =
            Map<String, dynamic>.from(decoded);

        final sessionToken = (responseBody is Map
                ? responseBody['token']
                : null)
            ?.toString()
            .trim();
        if (sessionToken == null || sessionToken.isEmpty || sessionToken == 'null') {
          setState(() => _isLoading = false);
          _setStatus(
            'Sign-in succeeded but the server did not return a session. Please ask the system administrator to check the login API.',
            Colors.redAccent,
          );
          return;
        }
        
        final rawUserData = responseBody['user'] ?? responseBody;
        if (rawUserData is! Map) {
          throw const FormatException('Login response did not contain a valid user object.');
        }
        final Map<String, dynamic> userData =
            Map<String, dynamic>.from(rawUserData);

        if (!userData.containsKey('fullName') && userData.containsKey('full_name')) {
          userData['fullName'] = userData['full_name'];
        }

        // 3. SECURITY GATE
        final String role = (userData['role'] ?? '').toString().toLowerCase();
        
        if (role.contains('admin') || role.contains('super') || role.contains('staff')) {
          await _routeToDashboard(sessionToken, userData);
        } else {
          setState(() => _isLoading = false);
          _setStatus('Access Denied: You do not have Staff or Admin privileges.', Colors.redAccent);
        }
      } else {
        setState(() => _isLoading = false);
        _setStatus(_serverErrorMessage(response), Colors.redAccent);
      }
    } on TimeoutException catch (error, stackTrace) {
      debugPrint('LOGIN timeout: $error\n$stackTrace');
      if (mounted) {
        setState(() => _isLoading = false);
        _setStatus(_exceptionMessage(error), _standardGold);
      }
    } on http.ClientException catch (error, stackTrace) {
      debugPrint('LOGIN HTTP client error: $error\n$stackTrace');
      if (mounted) {
        setState(() => _isLoading = false);
        _setStatus(_exceptionMessage(error), _standardGold);
      }
    } on FormatException catch (error, stackTrace) {
      debugPrint('LOGIN response format error: $error\n$stackTrace');
      if (mounted) {
        setState(() => _isLoading = false);
        _setStatus(_exceptionMessage(error), Colors.redAccent);
      }
    } catch (error, stackTrace) {
      debugPrint('LOGIN unexpected error (${error.runtimeType}): $error\n$stackTrace');
      if (mounted) {
        setState(() => _isLoading = false);
        _setStatus(_exceptionMessage(error), _standardGold);
      }
    }
  }

  Future<void> _routeToDashboard(String token, dynamic userData) async {
    ApiClient.bearerToken = token;
    await DatabaseService.saveToken(token);
    
    if (userData != null) {
      try {
        final localUser = LocalUser.fromJson(userData);
        await DatabaseService.saveLocalUser(localUser);
      } catch (e) {
        debugPrint('Failed to save user locally: $e');
      }
    }

    if (!mounted) return;

    // Show success message inside the card
    _setStatus('Login successful! Connecting...', _darkGreen);
    
    // 🚀 Wait just a moment so the user can read the success message before jumping
    await Future.delayed(const Duration(milliseconds: 800));

    if (!mounted) return;
    
    Navigator.pushReplacement(
      context,
      PageRouteBuilder(
        pageBuilder: (context, animation, secondaryAnimation) => const AdminHomeScreen(),
        transitionsBuilder: (context, animation, secondaryAnimation, child) {
          return FadeTransition(opacity: animation, child: child);
        },
        transitionDuration: const Duration(milliseconds: 500),
      ),
    );
  }

  Widget _buildInitialLoader() {
    return Center(
      key: const ValueKey('loader'), 
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          RotationTransition(
            turns: _spinController,
            child: Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: Colors.white,
                boxShadow: [
                  BoxShadow(color: Colors.black.withOpacity(0.1), blurRadius: 20, offset: const Offset(0, 5))
                ],
              ),
              child: const Icon(Icons.sync_rounded, color: _standardGold, size: 48), 
            ),
          ),
          const SizedBox(height: 24),
          const Text(
            'ESTABLISHING SECURE CONNECTION...',
            style: TextStyle(
              color: _darkGreen,
              fontWeight: FontWeight.bold,
              letterSpacing: 2.0,
              fontSize: 12,
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white.withOpacity(0.85), 
      body: AnimatedSwitcher(
        duration: const Duration(milliseconds: 600), 
        switchInCurve: Curves.easeOutCubic,
        switchOutCurve: Curves.easeInCubic,
        child: _isInitializing
            ? _buildInitialLoader()
            : Center(
                key: const ValueKey('form'), 
                child: FadeTransition(
                  opacity: _fadeAnimation,
                  child: SlideTransition(
                    position: _slideAnimation,
                    child: SingleChildScrollView(
                      child: Container(
                        width: 400, 
                        margin: const EdgeInsets.all(24),
                        padding: const EdgeInsets.symmetric(horizontal: 36, vertical: 48),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.zero, 
                          border: const Border(top: BorderSide(color: _standardGold, width: 4)), 
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black.withOpacity(0.10),
                              blurRadius: 30,
                              offset: const Offset(0, 10),
                            )
                          ],
                          image: DecorationImage(
                            image: const AssetImage('assets/logo.png'),
                            fit: BoxFit.contain,
                            alignment: Alignment.center,
                            colorFilter: ColorFilter.mode(
                              Colors.white.withOpacity(0.92), 
                              BlendMode.lighten,
                            ),
                          ),
                        ),
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            RichText(
                              textAlign: TextAlign.center,
                              text: const TextSpan(
                                children: [
                                  TextSpan(
                                    text: 'ROCKVIEW\n',
                                    style: TextStyle(
                                      fontSize: 26,
                                      fontWeight: FontWeight.w900,
                                      color: _darkGreen,
                                      letterSpacing: 2.0,
                                      height: 1.2,
                                    ),
                                  ),
                                  TextSpan(
                                    text: 'UNIVERSITY',
                                    style: TextStyle(
                                      fontSize: 18,
                                      fontWeight: FontWeight.bold,
                                      color: _standardGold,
                                      letterSpacing: 3.5,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            const SizedBox(height: 8),
                            Text(
                              'ADMINISTRATION PORTAL',
                              style: TextStyle(
                                fontSize: 11,
                                fontWeight: FontWeight.bold,
                                color: Colors.grey.shade500,
                                letterSpacing: 1.0,
                              ),
                            ),
                            const SizedBox(height: 32), // Adjusted spacing to fit status box

                            // --- 🚀 NEW: IN-CARD STATUS MESSAGE BOX ---
                            AnimatedSize(
                              duration: const Duration(milliseconds: 300),
                              curve: Curves.easeInOut,
                              child: _statusMessage == null
                                  ? const SizedBox(width: double.infinity) // Empty state
                                  : Container(
                                      width: double.infinity,
                                      margin: const EdgeInsets.only(bottom: 24),
                                      padding: const EdgeInsets.all(12),
                                      decoration: BoxDecoration(
                                        color: _statusColor!.withOpacity(0.08),
                                        border: Border.all(color: _statusColor!.withOpacity(0.5)),
                                      ),
                                      child: Row(
                                        children: [
                                          Icon(
                                            _statusColor == _darkGreen 
                                                ? Icons.check_circle_rounded 
                                                : Icons.error_outline_rounded,
                                            color: _statusColor,
                                            size: 20,
                                          ),
                                          const SizedBox(width: 12),
                                          Expanded(
                                            child: Text(
                                              _statusMessage!,
                                              style: TextStyle(
                                                color: _statusColor,
                                                fontWeight: FontWeight.w700,
                                                fontSize: 13,
                                                height: 1.4,
                                              ),
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                            ),

                            // --- USERNAME / EMAIL FIELD ---
                            _buildExactTextField(
                              controller: _emailController,
                              hint: 'Username or Email',
                              icon: Icons.person,
                            ),
                            const SizedBox(height: 16),

                            // --- PASSWORD FIELD ---
                            _buildExactTextField(
                              controller: _passwordController,
                              hint: 'Password',
                              icon: Icons.lock,
                              isPassword: true,
                            ),
                            const SizedBox(height: 32),

                            // --- LOGIN BUTTON ---
                            SizedBox(
                              width: double.infinity,
                              height: 50,
                              child: ElevatedButton(
                                onPressed: _isLoading ? null : _loginAndContinue,
                                style: ElevatedButton.styleFrom(
                                  backgroundColor: _darkGreen, 
                                  foregroundColor: Colors.white,
                                  elevation: 0,
                                  shape: const RoundedRectangleBorder(borderRadius: BorderRadius.zero),
                                ),
                                child: _isLoading 
                                    ? const SizedBox(height: 20, width: 20, child: CircularProgressIndicator(color: Colors.white, strokeWidth: 2))
                                    : const Text('SECURE LOGIN', style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold, letterSpacing: 1.0)),
                              ),
                            ),
                            const SizedBox(height: 20),

                            // --- FORGOT PASSWORD LINK ---
                            Align(
                              alignment: Alignment.centerRight,
                              child: InkWell(
                                onTap: () {
                                  // Handle forgot password route
                                },
                               child: Row(
  mainAxisSize: MainAxisSize.min,
  mainAxisAlignment: MainAxisAlignment.center,
  children: [
    Icon(Icons.warning_amber_rounded, size: 16, color: Colors.grey.shade600),
    const SizedBox(width: 6),
    Text(
      'System Under Surveillance',
      style: TextStyle(color: Colors.grey.shade600, fontSize: 13, fontWeight: FontWeight.w500),
    ),
  ],
),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ),
              ),
      ),
    );
  }

  // --- REPLICATED LAYOUT FIELD ---
  Widget _buildExactTextField({
    required TextEditingController controller,
    required String hint,
    required IconData icon,
    bool isPassword = false,
  }) {
    return Container(
      height: 48,
      decoration: BoxDecoration(
        border: Border.all(color: Colors.grey.shade300),
        color: const Color(0xFFF4F7F9), 
      ),
      child: Row(
        children: [
          Container(
            width: 48,
            color: Colors.grey.shade100,
            child: Center(
              child: Icon(icon, color: Colors.grey.shade500, size: 20),
            ),
          ),
          Container(width: 1, color: Colors.grey.shade300),
          Expanded(
            child: TextFormField(
              controller: controller,
              obscureText: isPassword && !_isPasswordVisible,
              style: const TextStyle(fontSize: 15, color: Colors.black87),
              decoration: InputDecoration(
                hintText: hint,
                hintStyle: TextStyle(color: Colors.grey.shade500, fontSize: 14),
                border: InputBorder.none,
                contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
                isDense: true,
                suffixIcon: isPassword
                    ? InkWell(
                        onTap: () => setState(() => _isPasswordVisible = !_isPasswordVisible),
                        child: Icon(
                          _isPasswordVisible ? Icons.visibility_off : Icons.visibility,
                          color: Colors.grey.shade600,
                          size: 20,
                        ),
                      )
                    : null,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
