import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:moneymgr_mobile/utils/pdf_utils.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

part 'pdf_viewer.g.dart';

@riverpod
Future<Uint8List> _renderPdf(
  Ref ref, {
  String? path,
  Uint8List? pdfBytes,
}) async {
  return renderPdf(path: path, pdfBytes: pdfBytes);
}

class PDFViewer extends ConsumerWidget {
  final String? pdfPath;
  final Uint8List? pdfBytes;
  final double? width;
  final double? height;
  final BoxFit? fit;

  const PDFViewer({
    super.key,
    this.pdfPath,
    this.pdfBytes,
    this.width,
    this.height,
    this.fit,
  }) : assert(pdfPath != null || pdfBytes != null);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final provider = ref.watch(
      _renderPdfProvider(path: pdfPath, pdfBytes: pdfBytes),
    );

    // Perform a switch-case on the result to handle loading/error states
    return switch (provider) {
      AsyncData(:final value) => Image(
        image: MemoryImage(value),
        width: width,
        height: height,
        fit: fit,
      ),
      AsyncError(:final error) => Text('PDF error: $error'),
      _ => Center(child: const CircularProgressIndicator()),
    };
  }
}
