import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../../../../widget/info_dialog.dart';
import '../bloc/loadable_state_bloc.dart';
import 'loadable_state_consumer.dart';

class LoadableStateErrorScreen extends StatelessWidget {
  final bool visible;
  final String? message;
  final String? technicalDetails;
  const LoadableStateErrorScreen({
    required this.visible,
    this.message,
    this.technicalDetails,
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    final bloc = context.watch<LoadableStateBloc>();
    final isOffline = bloc.connectivityStatusKnown() && !bloc.isConnected();
    final headline = isOffline
        ? bloc.connectionText()
        : (message ?? bloc.connectionText());

    return AnimatedOpacity(
      opacity: visible ? 1.0 : 0.0,
      duration: LoadableStateConsumer.animationDuration,
      curve: Curves.easeInOut,
      child: !visible
          ? null
          : Center(
              child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 24),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Icon(bloc.connectionIcon(), size: 40),
                    const SizedBox(height: 12),
                    Text(
                      headline,
                      style: const TextStyle(fontSize: 20),
                      textAlign: TextAlign.center,
                    ),
                    if (!isOffline &&
                        message != null &&
                        message != headline) ...[
                      const SizedBox(height: 8),
                      Text(
                        message!,
                        style: TextStyle(
                          color: Theme.of(context).hintColor,
                          fontSize: 14,
                        ),
                        textAlign: TextAlign.center,
                      ),
                    ],
                    if (bloc.allowRetry()) ...[
                      const SizedBox(height: 16),
                      TextButton(
                        onPressed: () => bloc.reFetch!(),
                        child: const Text('Erneut versuchen'),
                      ),
                    ],
                    if (technicalDetails != null) ...[
                      const SizedBox(height: 4),
                      TextButton(
                        onPressed: () => InfoDialog.show(
                          context,
                          technicalDetails!,
                          copyable: true,
                          title: 'Fehlerdetails',
                        ),
                        child: const Text('Details anzeigen'),
                      ),
                    ],
                  ],
                ),
              ),
            ),
    );
  }
}
