import 'dart:async';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:generp/Utils/commonWidgets.dart';
import 'package:syncfusion_flutter_pdfviewer/pdfviewer.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter_pdfview/flutter_pdfview.dart';
import 'package:http/http.dart' as http;
import 'dart:typed_data';

import '../../Utils/app_colors.dart';

class Fileviewer extends StatefulWidget {
  final String fileName;
  final String fileUrl;
  const Fileviewer({super.key, required this.fileName, required this.fileUrl});

  @override
  State<Fileviewer> createState() => _FileviewerState();
}

class _FileviewerState extends State<Fileviewer> {
  final Completer<InAppWebViewController> _controller =
      Completer<InAppWebViewController>();
  var empId = "";
  var sessionId = "";
  bool isLoading = true;
  InAppWebViewController? webViewController;
  PullToRefreshController? pullToRefreshController;
  PullToRefreshSettings pullToRefreshSettings = PullToRefreshSettings(
    color: AppColors.app_blue,
  );
  bool pullToRefreshEnabled = true;

  final GlobalKey webViewKey = GlobalKey();
  String getFileExtension(String fileName) {
    print(widget.fileUrl);
    return fileName.split('.').last.toLowerCase();
  }

  Future<void> _launchUrl(String url) async {
    final Uri uri = Uri.parse(url);
    if (await canLaunchUrl(uri)) {
      await launchUrl(uri, mode: LaunchMode.externalApplication);
    } else {
      throw 'Could not launch $url';
    }
  }

  var Finalurl;
  @override
  void initState() {
    //  loadData();
    pullToRefreshController =
        kIsWeb
            ? null
            : PullToRefreshController(
              settings: pullToRefreshSettings,
              onRefresh: () async {
                if (defaultTargetPlatform == TargetPlatform.android) {
                  webViewController?.reload();
                } else if (defaultTargetPlatform == TargetPlatform.iOS) {
                  webViewController?.loadUrl(
                    urlRequest: URLRequest(
                      url: await webViewController?.getUrl(),
                    ),
                  );
                }
              },
            );
    // print("URL:${widget.url}");
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: true,
      appBar: appbarNew(context, "File Viewer", 0xFFFFFFFF),
      body: SafeArea(child: Center(child: fileWidget(context))),
    );
  }

  Widget fileWidget(BuildContext context) {
    final extension = getFileExtension(widget.fileName);
    switch (extension) {
      case 'jpg':
      case 'jpeg':
      case 'png':
      case 'gif':
        return CachedNetworkImage(
          imageUrl: widget.fileUrl,
          placeholder:
              (context, url) =>
                  const Center(child: CircularProgressIndicator()),
          errorWidget: (context, url, error) => const Icon(Icons.error),
          fit: BoxFit.contain,
        );

      case 'pdf':
        return SfPdfViewer.network(widget.fileUrl, key: GlobalKey());

      case 'doc':
      case 'docx':
      case 'xls':
      case 'xlsx':
        return InAppWebView(
          initialUrlRequest: URLRequest(url: WebUri(widget.fileUrl)),
          androidOnGeolocationPermissionsShowPrompt: (
            InAppWebViewController controller,
            String origin,
          ) async {
            return GeolocationPermissionShowPromptResponse(
              origin: origin,
              allow: true,
              retain: true,
            );
          },
          initialOptions: InAppWebViewGroupOptions(
            android: AndroidInAppWebViewOptions(
              useWideViewPort: true,
              loadWithOverviewMode: true,
              allowContentAccess: true,
              geolocationEnabled: true,
              allowFileAccess: true,
              databaseEnabled: true, // Enables the WebView database
              domStorageEnabled: true, // Enables DOM storage
              builtInZoomControls: true, // Enables the built-in zoom controls
              displayZoomControls: false, // Disables displaying zoom controls
              safeBrowsingEnabled: true, // Enables Safe Browsing
              clearSessionCache: true,
            ),
            ios: IOSInAppWebViewOptions(allowsInlineMediaPlayback: true),
          ),

          androidOnPermissionRequest: (
            InAppWebViewController controller,
            String origin,
            List<String> resources,
          ) async {
            return PermissionRequestResponse(
              resources: resources,
              action: PermissionRequestResponseAction.GRANT,
            );
          },
          onWebViewCreated: (controller) {
            webViewController = controller;
            _controller.complete(controller);
          },
          pullToRefreshController: pullToRefreshController,
          onLoadStart: (controller, url) {
            return setState(() {
              isLoading = true;
            });
          },
          onLoadStop: (controller, url) {
            pullToRefreshController?.endRefreshing();
            return setState(() {
              isLoading = false;
            });
          },
          onReceivedError: (controller, request, error) {
            pullToRefreshController?.endRefreshing();
          },
          onProgressChanged: (controller, progress) {
            if (progress == 100) {
              pullToRefreshController?.endRefreshing();
            }
          },
          onConsoleMessage: (controller, consoleMessage) {
            if (kDebugMode) {
              debugPrint("consoleMessage$consoleMessage");
            }
            debugPrint("JavaScript console message: ${consoleMessage.message}");
          },
        );
      default:
        return Container();
    }
  }

  Future<Uint8List?> _loadPdf(String url) async {
    try {
      final response = await http.get(Uri.parse(url));
      if (response.statusCode == 200) {
        print(response.bodyBytes);
        return response.bodyBytes;
      }
    } catch (e) {
      print('Error loading PDF: $e');
    }
    return null;
  }
}
