import 'package:flutter/material.dart'; import 'package:lucide_icons/lucide_icons.dart'; import 'package:flutter_markdown_plus/flutter_markdown_plus.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; import '../../core/constants.dart'; import '../../core/theme.dart'; import '../../core/wikilink_syntax.dart'; import '../../providers/notes_provider.dart'; class NoteDetailScreen extends ConsumerWidget { final int noteId; // Provided when embedded in master-detail: called instead of context.pop(). final VoidCallback? onDeleted; const NoteDetailScreen({super.key, required this.noteId, this.onDeleted}); @override Widget build(BuildContext context, WidgetRef ref) { final noteAsync = ref.watch(noteDetailProvider(noteId)); final allNotes = ref.watch(notesProvider).value ?? []; void navigateByTitle(String title) { final matches = allNotes.where( (n) => n.title.toLowerCase() == title.toLowerCase(), ); if (matches.isNotEmpty) { context.push( Routes.noteDetail.replaceFirst(':id', '${matches.first.id}'), ); } else { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('Note not found: "$title"')), ); } } return Scaffold( appBar: AppBar( title: noteAsync.maybeWhen( data: (n) => Text(n.title), orElse: () => const Text('Note'), ), actions: [ noteAsync.maybeWhen( data: (note) => Row( children: [ IconButton( icon: const Icon(LucideIcons.pencil), onPressed: () => context.push( Routes.noteEdit.replaceFirst(':id', '$noteId'), ), ), IconButton( icon: const Icon(LucideIcons.trash2), onPressed: () async { final confirm = await showDialog( context: context, builder: (dialogContext) => AlertDialog( title: const Text('Delete note?'), actions: [ TextButton( onPressed: () => Navigator.pop(dialogContext, false), child: const Text('Cancel'), ), TextButton( onPressed: () => Navigator.pop(dialogContext, true), style: TextButton.styleFrom( foregroundColor: Theme.of(dialogContext) .extension()! .destructive, ), child: const Text('Delete'), ), ], ), ); if (confirm == true) { await ref.read(notesProvider.notifier).delete(noteId); if (context.mounted) { onDeleted != null ? onDeleted!() : context.pop(); } } }, ), ], ), orElse: () => const SizedBox.shrink(), ), ], ), body: noteAsync.when( loading: () => const Center(child: CircularProgressIndicator()), error: (e, _) => Center(child: Text('Error: $e')), data: (note) => Markdown( data: note.body, selectable: true, extensionSet: wikilinkExtensionSet, onTapLink: (text, href, _) { if (href == null) return; if (href.startsWith('wikilink://')) { navigateByTitle(Uri.decodeComponent(href.substring(11))); } }, ), ), ); } }