import 'package:flutter/material.dart';
import 'package:slrpg_app/l10n/app_localizations.dart';
import 'package:slrpg_app/src/core/theme/app_theme.dart';

class ErrorHandler {
  static String getReadableError(BuildContext context, Object error) {
    final l10n = AppLocalizations.of(context);
    if (l10n == null) return error.toString();

    final e = error.toString();

    // Check for network errors first, but be more specific
    if (e.contains('SocketException') ||
        e.contains('Connection refused') ||
        e.contains('HandshakeException') ||
        e.contains('Network is unreachable')) {
      return l10n.errorNoInternet;
    }

    if (e.contains('401') || e.contains('403')) {
      return l10n.errorUnauthorized;
    }

    if (e.contains('404')) {
      return l10n.errorNotFound;
    }

    // PocketBase often returns 400 for multiple things
    if (e.contains('400')) {
      if (e.contains('validation_not_unique')) {
        return l10n.errorEntryNotUnique;
      }
      // PocketBase specific error for failed login
      if (e.contains('Failed to authenticate') || e.contains('identity or password')) {
        return l10n.errorAuthenticationFailed;
      }
      return l10n.errorIllegalRequest;
    }

    return l10n.errorGeneric;
  }

  static void showErrorSnackBar(BuildContext context, Object error) {
    final scaffoldMessenger = ScaffoldMessenger.of(context);
    scaffoldMessenger.hideCurrentSnackBar();
    
    scaffoldMessenger.showSnackBar(
      SnackBar(
        content: Text(getReadableError(context, error)),
        backgroundColor: AppTheme.errorColor,
        behavior: SnackBarBehavior.floating,
        duration: const Duration(seconds: 4),
        dismissDirection: DismissDirection.horizontal, // Easier to swipe away
        margin: const EdgeInsets.fromLTRB(16, 16, 16, 60), // Move it up to not block navigation
        action: SnackBarAction(
          label: 'OK',
          textColor: Colors.white,
          onPressed: () {
            scaffoldMessenger.hideCurrentSnackBar();
          },
        ),
      ),
    );
  }
}
