import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:logger/logger.dart';

class FormKeyDebugger {
  static final Logger _logger = Logger();
  static final Map<String, GlobalKey> _trackedKeys = {};
  static final Set<String> _loggedCombinations = {};
  static DateTime? _lastDebugTime;
  static const Duration _debugCooldown = Duration(milliseconds: 500);

  /// Register a form key for tracking
  static void registerFormKey(String identifier, GlobalKey key) {
    if (!kDebugMode) return;

    _trackedKeys[identifier] = key;
    _logger.d('🔑 Registered form key: $identifier -> ${key.toString()}');
  }

  /// Debug all form keys with cooldown to prevent spam
  static void debugAllFormKeys() {
    if (!kDebugMode) return;

    final now = DateTime.now();
    if (_lastDebugTime != null &&
        now.difference(_lastDebugTime!) < _debugCooldown) {
      return; // Skip if called too frequently
    }
    _lastDebugTime = now;

    if (_trackedKeys.isEmpty) {
      _logger.d('🔍 No form keys registered for debugging');
      return;
    }

    _logger.d('🔍 === FORM KEY DEBUG SESSION ===');
    _logger.d('📊 Total tracked keys: ${_trackedKeys.length}');

    final keyGroups = <String, List<String>>{};
    final duplicates = <String>[];

    // Group keys by their string representation
    _trackedKeys.forEach((identifier, key) {
      final keyString = key.toString();
      keyGroups.putIfAbsent(keyString, () => []).add(identifier);

      _logger.d('🔑 $identifier: $keyString (hash: ${key.hashCode})');
      _logger.d(
        '   - Current context: ${key.currentContext != null ? "✅" : "❌"}',
      );

      if (key is GlobalKey<FormState>) {
        _logger.d('   - Form state: ${key.currentState != null ? "✅" : "❌"}');
        _logger.d('   - Form mounted: ${key.currentState?.mounted ?? false}');
      }
    });

    // Check for duplicates
    keyGroups.forEach((keyString, identifiers) {
      if (identifiers.length > 1) {
        duplicates.add(keyString);
        _logger.e('❌ DUPLICATE KEY DETECTED!');
        _logger.e('   Key: $keyString');
        _logger.e('   Used by: ${identifiers.join(", ")}');
      }
    });

    if (duplicates.isEmpty) {
      _logger.d('✅ No duplicate keys found');
    } else {
      _logger.e('❌ Found ${duplicates.length} duplicate key(s)');
    }

    _logger.d('🔍 === END DEBUG SESSION ===');
  }

  /// Debug a specific controller's form key
  static void debugControllerFormKey(String source, GlobalKey formKey) {
    if (!kDebugMode) return;

    final combination = '${source}_${formKey.toString()}';
    if (_loggedCombinations.contains(combination)) {
      return; // Already logged this combination
    }

    _loggedCombinations.add(combination);

    // Use microtask to avoid blocking UI
    Future.microtask(() {
      _logger.d(
        '🔑 Controller "$source" form key: $formKey (hashCode: ${formKey.hashCode})',
      );

      if (formKey is GlobalKey<FormState>) {
        _logger.d('   - Form state exists: ${formKey.currentState != null}');
        _logger.d(
          '   - Form mounted: ${formKey.currentState?.mounted ?? false}',
        );
      }
    });
  }

  /// Check if a key is already being tracked
  static bool isKeyTracked(GlobalKey key) {
    return _trackedKeys.containsValue(key);
  }

  /// Get all tracked keys
  static Map<String, GlobalKey> getTrackedKeys() {
    return Map.unmodifiable(_trackedKeys);
  }

  /// Clear all tracking (useful for testing)
  static void clearAll() {
    _trackedKeys.clear();
    _loggedCombinations.clear();
    _lastDebugTime = null;
    _logger.d('🧹 FormKeyDebugger cleared all tracking data');
  }

  /// Unregister a specific key
  static void unregisterFormKey(String identifier) {
    if (_trackedKeys.containsKey(identifier)) {
      _trackedKeys.remove(identifier);
      _logger.d('🗑️ Unregistered form key: $identifier');
    }
  }

  /// Validate form keys for common issues
  static void validateFormKeys() {
    if (!kDebugMode) return;

    _logger.d('🔍 Validating form keys...');

    final issues = <String>[];

    _trackedKeys.forEach((identifier, key) {
      // Check if key has context
      if (key.currentContext == null) {
        issues.add('$identifier: No context');
      }

      // Check if FormState key has state
      if (key is GlobalKey<FormState> && key.currentState == null) {
        issues.add('$identifier: No form state');
      }

      // Check if widget is mounted
      if (key is GlobalKey<FormState> &&
          key.currentState != null &&
          !key.currentState!.mounted) {
        issues.add('$identifier: Form not mounted');
      }
    });

    if (issues.isEmpty) {
      _logger.d('✅ All form keys are valid');
    } else {
      _logger.w('⚠️ Found ${issues.length} form key issue(s):');
      for (final issue in issues) {
        _logger.w('   - $issue');
      }
    }
  }

  /// Create a unique form key with automatic registration
  static GlobalKey<FormState> createFormKey(String identifier) {
    final key = GlobalKey<FormState>(debugLabel: identifier);
    registerFormKey(identifier, key);
    return key;
  }

  /// Create a unique form key with timestamp to prevent duplicates
  static GlobalKey<FormState> createUniqueFormKey(String identifier) {
    final timestamp = DateTime.now().millisecondsSinceEpoch;
    final uniqueId = '${identifier}_$timestamp';
    final key = GlobalKey<FormState>(debugLabel: uniqueId);
    registerFormKey(identifier, key);
    return key;
  }
}
