import 'package:flutter/material.dart';
import 'package:fotodocumentation/l10n/app_localizations.dart';
import 'package:fotodocumentation/controller/base_controller.dart';

class GeneralErrorWidget extends StatelessWidget {
  final String error;
  final Function()? reload;
  final int? statusCode;

  const GeneralErrorWidget({super.key, required this.error, this.reload, this.statusCode});

  factory GeneralErrorWidget.fromServerError(ServerError serverError, {Function()? reload}) {
    return GeneralErrorWidget(error: "", reload: reload, statusCode: serverError.statusCode);
  }

  factory GeneralErrorWidget.fromSnapshot(AsyncSnapshot snapshot, {Function()? reload}) {
    var error = snapshot.error;
    if (error is ServerError) {
      return GeneralErrorWidget.fromServerError(error, reload: () => reload);
    }
    return GeneralErrorWidget(error: snapshot.error.toString(), reload: () => reload);
  }

  @override
  Widget build(BuildContext context) {
    final localizations = AppLocalizations.of(context)!;
    final String errorMessage = statusCode != null
        ? localizations.errorWidgetStatusCode(statusCode!)
        : localizations.errorWidget(error);

    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(Icons.error_outline, size: 60, color: Colors.red[300]),
          Padding(
            padding: const EdgeInsets.only(top: 16),
            child: Text(
              errorMessage,
              style: TextStyle(color: Colors.red[700]),
              textAlign: TextAlign.center,
            ),
          ),
          const SizedBox(height: 16),
          if (reload != null) ...[
            ElevatedButton(
              onPressed: reload,
              child: Text(localizations.errorWidgetRetryButton),
            ),
          ],
        ],
      ),
    );
  }
}
