import 'dart:convert';
import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:webview_flutter/webview_flutter.dart';

class CustomYouTubePlayer extends StatefulWidget {
  final String videoId;
  final double aspectRatio;
  final double seekPosition; // Starting position of the video in seconds
  final Function? onVideoEnded; // Callback when the video ends
  final Widget? thumbnail; // Thumbnail image for the video
  final Color progressIndicatorColor; // Color of the progress indicator

  const CustomYouTubePlayer({
    required this.videoId,
    this.aspectRatio = 16 / 9,
    this.seekPosition = 0,
    this.onVideoEnded,
    this.thumbnail,
    this.progressIndicatorColor = Colors.red,
    super.key,
  });

  @override
  State<CustomYouTubePlayer> createState() => _CustomYouTubePlayerState();
}

class _CustomYouTubePlayerState extends State<CustomYouTubePlayer> {
  late final WebViewController _webViewController;
  bool _isLoading = true;
  bool _isPlaying = false;

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

    _webViewController = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..addJavaScriptChannel(
        'flutter_inappwebview',
        onMessageReceived: (JavaScriptMessage message) {
          if (message.message == 'onVideoEnded') {
            widget.onVideoEnded?.call();
          }
          try {
            Map<String, dynamic> data = jsonDecode(message.message);
            // Handle watched time and total watched time if needed
          } catch (e) {
            log("Error parsing JavaScript message: $e");
          }
        },
      )
      ..setNavigationDelegate(
        NavigationDelegate(
          onPageStarted: (String url) {
            setState(() => _isLoading = true);
          },
          onPageFinished: (String url) {
            setState(() => _isLoading = false);
          },
        ),
      );

    Future.delayed(Duration(milliseconds: 300), () {
      _webViewController.loadRequest(_buildVideoUri(widget.videoId, widget.seekPosition));
    });
  }

  Uri _buildVideoUri(String videoId, double seekPosition) {
    final htmlContent = '''
    <!DOCTYPE html>
    <html>
    <head>
      <style>
        html, body {
          margin: 0;
          padding: 0;
          height: 100%;
          background-color: black;
        }
        #youtube-player {
          width: 100%;
          height: 100%;
        }
      </style>
    </head>
    <body>
      <div id="youtube-player"></div>
      <script>
        var tag = document.createElement('script');
        tag.src = "https://www.youtube.com/iframe_api";
        var firstScriptTag = document.getElementsByTagName('script')[0];
        firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

        var player;
        function onYouTubeIframeAPIReady() {
          player = new YT.Player('youtube-player', {
            width: '100%',
            height: '100%',
            videoId: '$videoId',
            playerVars: {
              'autoplay': 1,
              'rel': 0,
              'playsinline': 1,
              'start': $seekPosition
            },
            events: {
              'onReady': onPlayerReady,
              'onStateChange': onPlayerStateChange
            }
          });
        }

        function onPlayerReady(event) {
          event.target.playVideo();
          setInterval(() => {
            if (player && player.getCurrentTime) {
              var watchedTime = player.getCurrentTime();
              var totalWatchedTime = player.getDuration();
              window.flutter_inappwebview.postMessage(JSON.stringify({
                watched_time: watchedTime,
                total_watched_time: totalWatchedTime
              }));
            }
          }, 1000);
        }

        function onPlayerStateChange(event) {
          if (event.data === YT.PlayerState.ENDED) {
            window.flutter_inappwebview.postMessage('onVideoEnded');
          }
        }
      </script>
    </body>
    </html>
    ''';

    return Uri.dataFromString(
      htmlContent,
      mimeType: 'text/html',
      encoding: Encoding.getByName('utf-8'),
    );
  }

  void _playVideo() {
    setState(() {
      _isPlaying = true;
    });
  }

  @override
  void dispose() {
    _webViewController.clearCache();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AspectRatio(
      aspectRatio: widget.aspectRatio,
      child: Stack(
        children: [
          if (widget.thumbnail != null && !_isPlaying) ...[
            widget.thumbnail!,
            Center(
              child: IconButton(
                icon: Icon(
                  Icons.play_circle_fill,
                  size: 64,
                  color: Colors.white,
                ),
                onPressed: _playVideo,
              ),
            ),
          ] else
            WebViewWidget(controller: _webViewController),
          if (_isLoading)
            Center(
              child: CircularProgressIndicator(
                color: widget.progressIndicatorColor,
              ),
            ),
        ],
      ),
    );
  }
}