import 'package:flutter/material.dart';
import 'package:flutter_pdfview/flutter_pdfview.dart';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';
import '/widget/snackbar_widget.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';

import '../app/constant.dart';

class PdfViewerPage extends StatefulWidget {
  final String courierID;
  final String date;

  const PdfViewerPage({super.key, required this.courierID, required this.date});
  @override
  _PdfViewerPageState createState() => _PdfViewerPageState();
}

class _PdfViewerPageState extends State<PdfViewerPage> {
  // final crr = widget.courierID;
  late File Pfile;
  bool isLoading = false;

  Future<void> loadNetwork() async {
    try {
      setState(() {
        isLoading = true;
      });
      // http: //10.9.9.3/birt/run?__report=report/one/rekap/rpt_total_order_kurir.rptdesign&__format=pdf&courierID=44&date=2023-09-07
      var url =
          "${Constant.baseBirtUrl}app-birt/run?__report=report/one/rekap/rpt_total_order_kurir.rptdesign&__format=pdf&courierID=${widget.courierID}&date=${widget.date}";
      final response = await http.get(Uri.parse(url));
      print(url);
      final bytes = response.bodyBytes;
      final filename = basename(url);
      final dir = await getApplicationDocumentsDirectory();
      var file = File('${dir.path}/$filename');
      await file.writeAsBytes(bytes, flush: true);
      setState(() {
        Pfile = file;
      });

      print(Pfile);
      setState(() {
        isLoading = false;
      });
    } catch (e) {
      print(e);
    }
  }

  @override
  void initState() {
    loadNetwork();

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "${widget.date}",
          style: TextStyle(fontWeight: FontWeight.bold),
        ),
      ),
      body: isLoading
          ? Center(child: CircularProgressIndicator())
          : Container(
              child: Center(
                child: PDFView(
                  filePath: Pfile.path,
                ),
              ),
            ),
    );
  }
}
