import 'package:chewie/chewie.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:video_player/video_player.dart';

class PlayerWidget extends StatefulWidget {
  const PlayerWidget({super.key});

  @override
  State<PlayerWidget> createState() => _PlayerWidgetState();
}

class _PlayerWidgetState extends State<PlayerWidget> {
  late VideoPlayerController videoPlayerController;
  late ChewieController chewieController;
  var videoUrl = Get.arguments["video_url"] == ""
      ? "https://player.vimeo.com/progressive_redirect/playback/930595309/rendition/360p/file.mp4?loc=external&signature=55ffa7ff72b807e1b3830cd6d308b092d4b1f82baadf6c20e7c235cd9a33bcdf"
      : Get.arguments["video_url"];
  @override
  void initState() {
    _initializePlayer();
    super.initState();
  }

  _initializePlayer() async {
    try {
      videoPlayerController = VideoPlayerController.networkUrl(
        Uri.parse(videoUrl),
      );

      await videoPlayerController.initialize();
      initChewie();
      setState(() {});
    } catch (e) {
      print("Error initializing video player: $e");
    }
  }

  initChewie() {
    chewieController = ChewieController(
        videoPlayerController: videoPlayerController,
        autoPlay: true,
        looping: false);
  }

  @override
  void dispose() {
    videoPlayerController.dispose();
    chewieController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return videoPlayerController != null &&
            videoPlayerController.value.isInitialized
        ? Scaffold(
            backgroundColor: Colors.black,
            appBar: AppBar(
              backgroundColor: Colors.black,
              leading: InkWell(
                onTap: () => Get.back(),
                child: Icon(
                  Icons.arrow_back_ios,
                  color: Colors.white,
                ),
              ),
            ),
            // CommonAppbar(titleTxt: ""),
            body: Center(
              child: AspectRatio(
                aspectRatio: videoPlayerController.value.aspectRatio,
                child: Chewie(
                  controller: chewieController,
                ),
              ),
            ),
          )
        : Center(child: CircularProgressIndicator());
  }
}
