import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cached_pdfview/flutter_cached_pdfview.dart';
import 'package:go_router/go_router.dart';

void showFilePreviewer(
  BuildContext context, {
  required String url,
}) {
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return FilePreviewer(
        url: url,
      );
    },
  );
}

class FilePreviewer extends StatelessWidget {
  final String url;

  const FilePreviewer({super.key, this.url = ""});

  bool _isImage(String suffix) {
    final lower = suffix.toLowerCase();
    return ['jpg', 'jpeg', 'png', 'gif', 'webp'].contains(lower);
  }

  bool _isPdf(String suffix) {
    return suffix.toLowerCase() == 'pdf';
  }

  @override
  Widget build(BuildContext context) {
    final suffix = url.split('.').last;
    Widget child;

    if (_isImage(suffix)) {
      child = InteractiveViewer(
        child: CachedNetworkImage(
          imageUrl: url,
          placeholder: (_, __) => const Center(
            child: CircularProgressIndicator(),
          ),
        ),
      );
    } else if (_isPdf(suffix)) {
      child = PDF(
        enableSwipe: true,
      ).cachedFromUrl(url);
    } else {
      child = const Text('不支持的文件类型');
    }
    return GestureDetector(
      onTap: () {
        context.pop();
      },
      child: Container(
        child: child,
      ),
    );
  }
}
