summaryrefslogtreecommitdiff
path: root/player-android/lib/screens/media_detail_screen.dart
blob: b4d7e1f1b0b0705079ef34dfdef8fe9e87f19522 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';

import '../api/player_api_client.dart';
import '../app_routes.dart';
import '../models/models.dart';
import '../providers/api_client_provider.dart';
import '../utils/error_mappers.dart';
import '../widgets/tag_picker.dart';
import 'create_share_dialog.dart';

// ---------------------------------------------------------------------------
// MediaDetailScreen
// ---------------------------------------------------------------------------

/// Displays a single media item with its title, full metadata (codec,
/// resolution, duration, file size), a thumbnail banner, a favourite toggle,
/// an interactive tag picker, and a play button that routes to the correct
/// player.
///
/// Design notes:
///   - [ConsumerStatefulWidget] is used so we can hold local loading/error
///     state, guard async continuations with [mounted], and call [setState]
///     to trigger rebuilds after the favourite toggle.
///   - [getMedia] is called from [initState] (via a post-frame callback so the
///     Riverpod ref is fully bound) and on pull-to-refresh.
///   - No `dio` import — error mapping is delegated to [mediaDetailErrorMessage]
///     in `error_mappers.dart` (Dependency Inversion Principle).
///   - The screen is split into multiple focused sub-widgets so the state
///     class stays well under 50 lines.
///   - Tag management (add/remove/autocomplete) is extracted to [TagPicker]
///     (Single Responsibility); the screen only wires the client through.
class MediaDetailScreen extends ConsumerStatefulWidget {
  /// The string form of the media ID extracted from the '/media/:id' route.
  final String mediaId;

  const MediaDetailScreen({super.key, required this.mediaId});

  @override
  ConsumerState<MediaDetailScreen> createState() => _MediaDetailScreenState();
}

class _MediaDetailScreenState extends ConsumerState<MediaDetailScreen> {
  // Nullable: null means the first load has not completed yet.
  Media? _media;

  // Non-null when the last load attempt failed.
  String? _error;

  // True while a getMedia call is in flight (shows the full-screen spinner).
  bool _isLoading = false;

  // True while a toggleFavorite call is in flight; prevents concurrent taps
  // from queuing up multiple API calls that could result in a desync.
  bool _isFavoriteLoading = false;

  @override
  void initState() {
    super.initState();
    // Defer the first load until after the first frame so [ref] is fully bound
    // and any provider overrides in the test environment are applied.
    WidgetsBinding.instance.addPostFrameCallback((_) => _load());
  }

  // ---------------------------------------------------------------------------
  // Data loading
  // ---------------------------------------------------------------------------

  /// Fetches the media item from the server and updates local state.
  ///
  /// Called on first mount and on pull-to-refresh.  Errors are mapped by the
  /// top-level [mediaDetailErrorMessage] helper so no `dio` import is needed.
  Future<void> _load() async {
    if (!mounted) return;
    setState(() {
      _isLoading = true;
      _error = null;
    });

    try {
      final id = int.tryParse(widget.mediaId) ?? 0;
      final client = ref.read(apiClientProvider);
      final media = await client.getMedia(id);
      if (!mounted) return;
      setState(() {
        _media = media;
        _isLoading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _error = mediaDetailErrorMessage(e);
        _isLoading = false;
      });
    }
  }

  // ---------------------------------------------------------------------------
  // Favourite toggle
  // ---------------------------------------------------------------------------

  /// Calls [toggleFavorite] on the server and reflects the new state locally.
  ///
  /// The server returns the new favourite state; we apply it to the in-memory
  /// [_media] copy so the UI updates immediately without a full reload.
  /// If the call fails, a snack-bar is shown and the toggle is reverted
  /// (the local state was not yet changed, so no explicit revert is needed).
  ///
  /// [_isFavoriteLoading] is set to true for the duration of the call to block
  /// concurrent taps that could otherwise race and desync the UI with the server.
  Future<void> _toggleFavorite() async {
    final media = _media;
    // Guard against concurrent taps and against toggling before data is loaded.
    if (media == null || _isFavoriteLoading) return;

    setState(() => _isFavoriteLoading = true);

    // Optimistically flip the favourite flag in local state so the icon
    // updates instantly without waiting for the round-trip.
    final newFavorite = !media.favorite;
    if (!mounted) return;
    setState(() {
      _media = _buildMediaWithFavorite(media, newFavorite);
    });

    try {
      final client = ref.read(apiClientProvider);
      final confirmed = await client.toggleFavorite(media.id);
      if (!mounted) return;
      // Reconcile with the value the server actually stored.
      setState(() {
        _media = _buildMediaWithFavorite(_media!, confirmed);
      });
    } catch (e) {
      if (!mounted) return;
      // Revert the optimistic update on failure.
      setState(() {
        _media = _buildMediaWithFavorite(_media!, media.favorite);
      });
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Could not update favourite. Try again.')),
      );
    } finally {
      if (mounted) setState(() => _isFavoriteLoading = false);
    }
  }

  /// Returns a copy of [media] with [favorite] replaced.
  ///
  /// [Media] is immutable so we reconstruct it via [Media.fromJson]/[toJson]
  /// to avoid adding a `copyWith` method to the model layer.
  Media _buildMediaWithFavorite(Media media, bool favorite) {
    final json = media.toJson()..['favorite'] = favorite;
    return Media.fromJson(json);
  }

  // ---------------------------------------------------------------------------
  // Notes navigation
  // ---------------------------------------------------------------------------

  /// Navigates to [NotesEditorScreen] for the current media item.
  ///
  /// Uses [AppRoutes.notesPath] so the routing logic stays in one place
  /// (Open-Closed: no URL construction scattered across the screen).
  void _openNotes() {
    final media = _media;
    if (media == null) return;
    context.go(AppRoutes.notesPath(media.id.toString()));
  }

  // ---------------------------------------------------------------------------
  // Share
  // ---------------------------------------------------------------------------

  /// Opens [showCreateShareDialog] for the current media item.
  ///
  /// Delegates all share logic (date picker, max uses, clipboard copy) to
  /// [CreateShareDialog] so this class remains focused on media display and
  /// navigation (Single Responsibility).  The injected [PlayerApiClient] is
  /// passed directly so the dialog never needs its own provider read — keeping
  /// the dialog provider-free and independently testable (Dependency Inversion).
  Future<void> _share() async {
    final media = _media;
    if (media == null || !mounted) return;

    final client = ref.read(apiClientProvider);
    // showCreateShareDialog is async; the mounted check after the await guards
    // against the widget being disposed while the dialog is open.
    await showCreateShareDialog(
      context,
      mediaId: media.id,
      client: client,
    );
    // No post-dialog state update needed: the dialog handles clipboard copy
    // and the SnackBar internally.
  }

  // ---------------------------------------------------------------------------
  // Navigation
  // ---------------------------------------------------------------------------

  /// Routes to the video or audio player based on [media.type].
  ///
  /// The stream URL is obtained via [PlayerApiClient.streamUrl] — keeping the
  /// API path in one place and preventing Dio internals from leaking into the
  /// UI layer (Dependency Inversion).  The URL is passed as a route extra so
  /// the player screen can start playback without a second API call.
  void _play() {
    final media = _media;
    if (media == null) return;

    final client = ref.read(apiClientProvider);
    // Delegate URL construction to the client; avoids coupling the screen to
    // the underlying Dio base URL or request structure.
    final streamUrl = client.streamUrl(media.id);

    if (media.type == 'video') {
      context.go(
        AppRoutes.videoPlayerPath(media.id.toString()),
        extra: streamUrl,
      );
    } else {
      // audio / podcast / unknown — default to the audio player.
      context.go(
        AppRoutes.audioPlayerPath(media.id.toString()),
        extra: streamUrl,
      );
    }
  }

  // ---------------------------------------------------------------------------
  // Build
  // ---------------------------------------------------------------------------

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _buildAppBar(),
      body: _buildBody(context),
    );
  }

  /// Builds the app bar with title and a three-dot overflow menu.
  ///
  /// The overflow menu contains "Notes" and "Share" actions.  Using a
  /// [PopupMenuButton] keeps the pattern open for future items without layout
  /// changes.  The [onSelected] callback uses a [Map]-based dispatch so adding
  /// a new action requires only a new enum value and one map entry — no
  /// if/else chain to extend (Open-Closed Principle).  All actions are
  /// disabled while media is still loading (null) to prevent calling the API
  /// with a stale ID.
  AppBar _buildAppBar() {
    return AppBar(
      title: Text(_media?.fileName ?? 'Media ${widget.mediaId}'),
      actions: [
        PopupMenuButton<_MenuAction>(
          key: const Key('media_detail_overflow_menu'),
          onSelected: (action) {
            // Map-based dispatch: adding a new menu action requires only a new
            // enum value, a handler method, and one entry here — no if/else
            // chain to extend (Open-Closed Principle).
            final handlers = <_MenuAction, VoidCallback>{
              _MenuAction.notes: _openNotes,
              _MenuAction.share: _share,
            };
            handlers[action]?.call();
          },
          itemBuilder: (_) => [
            PopupMenuItem<_MenuAction>(
              key: const Key('media_detail_notes_menu_item'),
              // Disable the item until media has loaded so the mediaId is valid.
              enabled: _media != null,
              value: _MenuAction.notes,
              child: const ListTile(
                leading: Icon(Icons.notes_outlined),
                title: Text('Notes'),
                contentPadding: EdgeInsets.zero,
              ),
            ),
            PopupMenuItem<_MenuAction>(
              key: const Key('media_detail_share_menu_item'),
              // Disable the item until media has loaded so the mediaId is valid.
              enabled: _media != null,
              value: _MenuAction.share,
              child: const ListTile(
                leading: Icon(Icons.share),
                title: Text('Share'),
                contentPadding: EdgeInsets.zero,
              ),
            ),
          ],
        ),
      ],
    );
  }

  /// Delegates to the appropriate state widget based on loading/error/data.
  Widget _buildBody(BuildContext context) {
    // Full-screen spinner only on the very first load (no data yet).
    if (_isLoading && _media == null) {
      return const Center(
        key: Key('media_detail_loading'),
        child: CircularProgressIndicator(),
      );
    }

    if (_error != null) {
      return _ErrorView(
        message: _error!,
        onRetry: _load,
      );
    }

    if (_media == null) {
      // Should not happen in normal flow, but guard defensively.
      return const SizedBox.shrink();
    }

    final client = ref.read(apiClientProvider);
    return RefreshIndicator(
      onRefresh: _load,
      child: _MediaDetailContent(
        media: _media!,
        thumbnailUrl: client.thumbnailUrl(_media!.id),
        onFavoriteToggle: _toggleFavorite,
        onPlay: _play,
        // Pass the client so _MediaDetailContent can hand it to TagPicker;
        // this avoids TagPicker needing its own provider read (DIP).
        client: client,
      ),
    );
  }
}

// ---------------------------------------------------------------------------
// _MenuAction
// ---------------------------------------------------------------------------

/// Enum of available overflow-menu actions in [MediaDetailScreen].
///
/// Using a typed enum (rather than raw strings) makes [PopupMenuButton] type
/// safe and avoids stringly-typed comparisons in [onSelected] (type safety /
/// Open-Closed: add new actions here without touching the menu-builder switch).
enum _MenuAction { notes, share }

// ---------------------------------------------------------------------------
// _MediaDetailContent
// ---------------------------------------------------------------------------

/// Scrollable body of the media detail screen.
///
/// Extracted from [_MediaDetailScreenState] so the state class stays concise
/// and this widget is independently testable.  All callbacks and the API
/// client are injected so this widget has no direct dependency on providers
/// or navigation (Dependency Inversion, Single Responsibility).
class _MediaDetailContent extends StatelessWidget {
  const _MediaDetailContent({
    required this.media,
    required this.thumbnailUrl,
    required this.onFavoriteToggle,
    required this.onPlay,
    required this.client,
  });

  final Media media;

  /// Pre-computed thumbnail URL so this widget stays provider-free.
  final String thumbnailUrl;

  /// Called when the favourite icon button is tapped.
  final VoidCallback onFavoriteToggle;

  /// Called when the play button is tapped.
  final VoidCallback onPlay;

  /// API client injected so [TagPicker] can call [addTag] / [removeTag] /
  /// [listTags] without reading from a provider directly (DIP).
  final PlayerApiClient client;

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      physics: const AlwaysScrollableScrollPhysics(),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          // Full-width thumbnail/cover image.
          _ThumbnailBanner(thumbnailUrl: thumbnailUrl, type: media.type),

          Padding(
            padding: const EdgeInsets.fromLTRB(16, 12, 16, 0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // Title + favourite toggle on the same row.
                _TitleRow(
                  title: media.fileName,
                  isFavorite: media.favorite,
                  onFavoriteToggle: onFavoriteToggle,
                ),

                const SizedBox(height: 8),

                // Codec · resolution · duration · file size.
                _MetadataRow(media: media),

                // Interactive tag picker: existing tags as deletable chips
                // plus an autocomplete input for adding new tags.
                // Always shown so users can add tags even when none exist yet.
                const SizedBox(height: 12),
                TagPicker(
                  key: const Key('media_detail_tags'),
                  mediaId: media.id,
                  tags: media.tags,
                  client: client,
                ),

                const SizedBox(height: 24),
              ],
            ),
          ),

          // Play button anchored at the bottom of the scrollable area.
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            child: _PlayButton(type: media.type, onPlay: onPlay),
          ),

          const SizedBox(height: 24),
        ],
      ),
    );
  }
}

// ---------------------------------------------------------------------------
// _ThumbnailBanner
// ---------------------------------------------------------------------------

/// Full-width hero image at the top of the detail screen.
///
/// Falls back to an icon placeholder when [thumbnailUrl] is empty or the
/// network request fails — mirrors the card thumbnail pattern from
/// [MediaGridScreen] for visual consistency.
class _ThumbnailBanner extends StatelessWidget {
  const _ThumbnailBanner({required this.thumbnailUrl, required this.type});

  final String thumbnailUrl;

  /// Media type string used to choose the placeholder icon.
  final String type;

  @override
  Widget build(BuildContext context) {
    return AspectRatio(
      // 16:9 for video; square-ish (4:3) for audio/other for visual variety.
      aspectRatio: type == 'video' ? 16 / 9 : 4 / 3,
      child: thumbnailUrl.isEmpty
          ? _placeholder(context)
          : CachedNetworkImage(
              key: const Key('media_detail_thumbnail'),
              imageUrl: thumbnailUrl,
              fit: BoxFit.cover,
              placeholder: (_, __) =>
                  const Center(child: CircularProgressIndicator()),
              errorWidget: (_, __, ___) => _placeholder(context),
            ),
    );
  }

  /// Colored box with a type-appropriate icon when no thumbnail is available.
  Widget _placeholder(BuildContext context) {
    final icon = type == 'video'
        ? Icons.videocam_outlined
        : type == 'audio'
            ? Icons.headphones_outlined
            : Icons.image_outlined;

    return ColoredBox(
      color: Theme.of(context).colorScheme.surfaceContainerHighest,
      child: Icon(
        icon,
        size: 72,
        color: Theme.of(context).colorScheme.onSurfaceVariant,
      ),
    );
  }
}

// ---------------------------------------------------------------------------
// _TitleRow
// ---------------------------------------------------------------------------

/// Row containing the media title and a favourite toggle icon button.
///
/// The favourite icon is filled when [isFavorite] is true, outlined otherwise.
/// Tapping calls [onFavoriteToggle] — the actual API call and state update are
/// handled by the parent state class.
class _TitleRow extends StatelessWidget {
  const _TitleRow({
    required this.title,
    required this.isFavorite,
    required this.onFavoriteToggle,
  });

  final String title;
  final bool isFavorite;
  final VoidCallback onFavoriteToggle;

  @override
  Widget build(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Expanded(
          child: Text(
            title,
            key: const Key('media_detail_title'),
            style: Theme.of(context).textTheme.titleLarge,
          ),
        ),
        IconButton(
          key: const Key('media_detail_favorite'),
          icon: Icon(
            isFavorite ? Icons.favorite : Icons.favorite_border,
            color: isFavorite
                ? Theme.of(context).colorScheme.error
                : Theme.of(context).colorScheme.onSurfaceVariant,
          ),
          tooltip: isFavorite ? 'Remove from favourites' : 'Add to favourites',
          onPressed: onFavoriteToggle,
        ),
      ],
    );
  }
}

// ---------------------------------------------------------------------------
// _MetadataRow
// ---------------------------------------------------------------------------

/// Horizontal row of codec · resolution · duration · file-size chips.
///
/// Renders each non-empty value as a compact text badge separated by a
/// centred dot divider.  Empty or zero values are omitted to avoid noise
/// (e.g. audio items have no meaningful resolution).
class _MetadataRow extends StatelessWidget {
  const _MetadataRow({required this.media});

  final Media media;

  @override
  Widget build(BuildContext context) {
    final parts = _buildParts();
    if (parts.isEmpty) return const SizedBox.shrink();

    return Wrap(
      key: const Key('media_detail_metadata'),
      spacing: 4,
      runSpacing: 4,
      children: [
        for (int i = 0; i < parts.length; i++) ...[
          if (i > 0)
            Text(
              '·',
              style: Theme.of(context).textTheme.bodySmall?.copyWith(
                    color: Theme.of(context).colorScheme.onSurfaceVariant,
                  ),
            ),
          Text(
            parts[i],
            style: Theme.of(context).textTheme.bodySmall?.copyWith(
                  color: Theme.of(context).colorScheme.onSurfaceVariant,
                ),
          ),
        ],
      ],
    );
  }

  /// Collects non-empty metadata strings to display.
  List<String> _buildParts() {
    final parts = <String>[];
    if (media.codec.isNotEmpty) parts.add(media.codec);
    if (media.resolution.isNotEmpty) parts.add(media.resolution);
    if (media.duration > 0) parts.add(_formatDuration(media.duration));
    if (media.fileSizeBytes > 0) parts.add(_formatFileSize(media.fileSizeBytes));
    return parts;
  }

  /// Formats [seconds] as `h:mm:ss` or `m:ss`.
  static String _formatDuration(double seconds) {
    final total = seconds.truncate();
    final h = total ~/ 3600;
    final m = (total % 3600) ~/ 60;
    final s = total % 60;
    if (h > 0) {
      return '$h:${m.toString().padLeft(2, '0')}:${s.toString().padLeft(2, '0')}';
    }
    return '$m:${s.toString().padLeft(2, '0')}';
  }

  /// Formats [bytes] as a human-readable size string (KB, MB, GB).
  static String _formatFileSize(int bytes) {
    if (bytes >= 1073741824) {
      return '${(bytes / 1073741824).toStringAsFixed(1)} GB';
    }
    if (bytes >= 1048576) {
      return '${(bytes / 1048576).toStringAsFixed(1)} MB';
    }
    return '${(bytes / 1024).toStringAsFixed(0)} KB';
  }
}

// ---------------------------------------------------------------------------
// _PlayButton
// ---------------------------------------------------------------------------

/// Full-width play button at the bottom of the detail screen.
///
/// Shows a video or audio icon depending on [type].  Calls [onPlay] when
/// tapped; routing to the correct player is the parent's responsibility
/// (Single Responsibility: this widget only concerns itself with the button
/// appearance and callback delegation).
class _PlayButton extends StatelessWidget {
  const _PlayButton({required this.type, required this.onPlay});

  final String type;
  final VoidCallback onPlay;

  @override
  Widget build(BuildContext context) {
    final isVideo = type == 'video';
    return FilledButton.icon(
      key: const Key('media_detail_play'),
      onPressed: onPlay,
      icon: Icon(isVideo ? Icons.play_circle_outline : Icons.headphones),
      label: Text(isVideo ? 'Play Video' : 'Play Audio'),
      style: FilledButton.styleFrom(
        minimumSize: const Size.fromHeight(48),
      ),
    );
  }
}

// ---------------------------------------------------------------------------
// _ErrorView
// ---------------------------------------------------------------------------

/// Full-screen error view with a retry button.
///
/// Shown when [getMedia] throws.  The [message] comes from
/// [mediaDetailErrorMessage], which maps exceptions to human-readable strings.
class _ErrorView extends StatelessWidget {
  const _ErrorView({required this.message, required this.onRetry});

  final String message;
  final VoidCallback onRetry;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Padding(
        padding: const EdgeInsets.all(24),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.error_outline,
              size: 56,
              color: Theme.of(context).colorScheme.error,
            ),
            const SizedBox(height: 16),
            Text(
              message,
              key: const Key('media_detail_error'),
              textAlign: TextAlign.center,
              style: Theme.of(context).textTheme.bodyLarge,
            ),
            const SizedBox(height: 24),
            ElevatedButton.icon(
              key: const Key('media_detail_retry'),
              onPressed: onRetry,
              icon: const Icon(Icons.refresh),
              label: const Text('Retry'),
            ),
          ],
        ),
      ),
    );
  }
}