import 'dart:io';

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

class PDFViewer extends StatefulWidget {
  final bool localFile;
  final File? file;
  final String? url;

  const PDFViewer({Key? key,
    required this.localFile,
    this.file,
    this.url
  }) : super(key: key);

  @override
  _PDFViewerState createState() => _PDFViewerState();
}

class _PDFViewerState extends State<PDFViewer> {
 late  PdfViewerController _pdfViewerController;
  bool _multiplePages = false;

  @override
  void initState() {
    super.initState();

    _pdfViewerController = PdfViewerController();
  }

  @override
  Widget build(BuildContext context) {
    final path = widget.localFile ? widget.file!.path.split('/') : widget.url!.split('/');
    return Scaffold(
      appBar: AppBar(
        centerTitle: false,
        title: Text(
          widget.localFile ? path.last : path.last.replaceAll("%20", ""),
          textAlign: TextAlign.center,
          style: const TextStyle(
            color: Colors.white,
            fontFamily: 'Helvetica Neue Black Cond',
          ),
        ),
        actions: <Widget>[
          IconButton(
            icon: const Icon(
              Icons.share,
              color: Colors.white,
            ),
            onPressed: (){
              String? pathToShare = widget.localFile ? widget.file!.path : widget.url;
              if(widget.localFile){
                Share.shareFiles([pathToShare!], text: path.last);
              }else{
                Share.share(widget.url!, subject: path.last.replaceAll("%20", ""));
              }
            },
          ),
          if(_multiplePages)
            IconButton(
              icon: const Icon(
                Icons.keyboard_arrow_up,
                color: Colors.white,
              ),
              onPressed: () {
                _pdfViewerController.previousPage();
              },
            ),
          if(_multiplePages)
            IconButton(
              icon: const Icon(
                Icons.keyboard_arrow_down,
                color: Colors.white,
              ),
              onPressed: () {
                _pdfViewerController.nextPage();
              },
            )
        ],
      ),
      body: widget.localFile ? SfPdfViewer.file(
        widget.file!,
        controller: _pdfViewerController,
        searchTextHighlightColor: Colors.redAccent,
        onDocumentLoaded: (details) => setState(() => _multiplePages = details.document.pages.count > 1),
      ) : SfPdfViewer.network(
        widget.url!,
        controller: _pdfViewerController,
        searchTextHighlightColor: Colors.redAccent,
        onDocumentLoaded: (details) => setState(() => _multiplePages = details.document.pages.count > 1),
      ),
    );
  }
}
