import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_pdfviewer/pdfviewer.dart';

import '../../../api/marianumconnect/queries/get_newsletter_file/get_newsletter_file.dart';
import '../../../widget/app_progress_indicator.dart';
import '../../../widget/confirm_dialog.dart';
import '../../../widget/placeholder_view.dart';
import '../../../widget/route_transition_gate.dart';

class MessageView extends StatefulWidget {
  final String id;
  final String title;
  const MessageView({super.key, required this.id, required this.title});

  @override
  State<MessageView> createState() => _MessageViewState();
}

class _MessageViewState extends State<MessageView> {
  late final Future<Uint8List> _pdf = GetNewsletterFile(widget.id).run();

  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: Text(widget.title)),
    body: FutureBuilder<Uint8List>(
      future: _pdf,
      builder: (context, snapshot) {
        if (snapshot.hasError) {
          return const PlaceholderView(
            icon: Icons.error_outline,
            text: 'Das Dokument konnte nicht geladen werden.',
          );
        }
        if (!snapshot.hasData) {
          return const Center(child: AppProgressIndicator.large());
        }
        return RouteTransitionGate(
          builder: (context) => SfPdfViewer.memory(
            snapshot.data!,
            enableHyperlinkNavigation: true,
            onHyperlinkClicked: (PdfHyperlinkClickedDetails e) =>
                ConfirmDialog.openBrowser(context, e.uri),
          ),
        );
      },
    ),
  );
}
