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();

    if (e.contains('SocketException') ||
        e.contains('Connection refused') ||
        e.contains('ClientException') ||
        e.contains('HandshakeException')) {
      return l10n.errorNoInternet;
    }

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

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

    if (e.contains('400')) {
      if (e.contains('validation_not_unique')) {
        return l10n.errorEntryNotUnique;
      }
      if (e.contains('Failed to authenticate')) {
        return l10n.errorAuthenticationFailed;
      }
      return l10n.errorIllegalRequest;
    }

    return l10n.errorGeneric;
  }

  static void showErrorSnackBar(BuildContext context, Object error) {
    ScaffoldMessenger.of(context).hideCurrentSnackBar();
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(getReadableError(context, error)),
        backgroundColor: AppTheme.errorColor,
        behavior: SnackBarBehavior.floating,
        duration: const Duration(seconds: 4),
        action: SnackBarAction(
          label: 'OK',
          textColor: Colors.white,
          onPressed: () => ScaffoldMessenger.of(context).hideCurrentSnackBar(),
        ),
      ),
    );
  }
}
