import 'package:flick_video_player/flick_video_player.dart';
import 'package:flutter/material.dart';
import 'package:visibility_detector/visibility_detector.dart';
import 'package:video_player/video_player.dart';

class MobileVideoPlayer extends StatefulWidget {
  MobileVideoPlayer({
    Key? key,
    required this.url,
    this.onLoaded,
  }) : super(key: key);

  final String url;

  final VoidCallback? onLoaded;

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

class _PlayerState extends State<MobileVideoPlayer> {
  late FlickManager flickManager;

  bool isLoaded = false;

  @override
  void initState() {
    super.initState();
    flickManager = FlickManager(
      videoPlayerController: VideoPlayerController.networkUrl(
        Uri.parse(widget.url),
        videoPlayerOptions: VideoPlayerOptions(),
      ),
    );
    flickManager.flickVideoManager!.addListener(() {
      if (!isLoaded && flickManager.flickVideoManager!.isPlaying) {
        widget.onLoaded?.call();
        isLoaded = true;
      }
    });
  }

  @override
  void dispose() {
    flickManager.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return VisibilityDetector(
      key: ObjectKey(flickManager),
      onVisibilityChanged: (visibility) {
        if (visibility.visibleFraction == 0 && mounted) {
          flickManager.flickControlManager?.autoPause();
        } else if (visibility.visibleFraction == 1) {
          flickManager.flickControlManager?.autoResume();
        }
      },
      child: FlickVideoPlayer(
        flickManager: flickManager,
        flickVideoWithControls: const FlickVideoWithControls(
          videoFit: BoxFit.contain,
          closedCaptionTextStyle: TextStyle(fontSize: 8),
          controls: FlickPortraitControls(),
        ),
        flickVideoWithControlsFullscreen: const FlickVideoWithControls(
          videoFit: BoxFit.contain,
          controls: FlickLandscapeControls(),
        ),
      ),
    );
  }
}
