import 'package:flutter/material.dart';
import '../components/error/error_content.dart';

class ErrorService {
  static final ErrorService _instance = ErrorService._internal();
  factory ErrorService() => _instance;
  ErrorService._internal();

  // GlobalKey pour accéder au context depuis n'importe où
  static GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

  // Afficher une erreur en dialog
  void showError({
    required String message,
    String title = 'Erreur',
    VoidCallback? onRetry,
    IconData icon = Icons.error_outline,
    Color? iconColor,
  }) {
    final context = navigatorKey.currentContext;
    if (context != null) {
      showErrorDialog(
        context,
        title: title,
        message: message,
        icon: icon,
        iconColor: iconColor,
        onRetry: onRetry,
      );
    }
  }

  // Afficher une erreur en snackbar
  void showSnackbar({
    required String message,
    VoidCallback? onRetry,
    bool isError = true,
  }) {
    final context = navigatorKey.currentContext;
    if (context != null) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(message),
          backgroundColor: isError ? Colors.red[400] : Colors.green[600],
          duration: const Duration(seconds: 4),
          action: onRetry != null
              ? SnackBarAction(
                  label: 'Réessayer',
                  textColor: Colors.white,
                  onPressed: onRetry,
                )
              : null,
          behavior: SnackBarBehavior.floating,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(10),
          ),
        ),
      );
    }
  }

  // Logger dans la console (développement)
  void logError(String source, dynamic error, [StackTrace? stackTrace]) {
    print('═══════════════════════════════════');
    print('❌ ERREUR dans $source');
    print('Message: $error');
    if (stackTrace != null) {
      print('StackTrace: $stackTrace');
    }
    print('═══════════════════════════════════');
  }

  // Logger une info (développement)
  void logInfo(String source, String message) {
    print('ℹ️ [$source] $message');
  }

  // Logger un succès
  void logSuccess(String source, String message) {
    print('✅ [$source] $message');
  }
}