// ignore_for_file: deprecated_member_use

import 'package:chewie/chewie.dart';

import 'package:flutter/material.dart';
import 'package:hoshan/ui/widgets/sections/loading/default_placeholder.dart';
import 'package:video_player/video_player.dart';

class ChatVideoPlayer extends StatefulWidget {
  final String src;
  final Widget? custome;
  final bool showOptions;
  const ChatVideoPlayer(
      {super.key, required this.src, this.custome, this.showOptions = false});

  @override
  State<ChatVideoPlayer> createState() => _ChatVideoPlayerState();
}

class _ChatVideoPlayerState extends State<ChatVideoPlayer> {
  late VideoPlayerController _videoPlayerController;
  ChewieController? _chewieController;

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

  Future<void> _handleVideoPlayback() async {
    _videoPlayerController = VideoPlayerController.network(widget.src);

    await _videoPlayerController.initialize().then((_) {
      setState(() {
        _chewieController = ChewieController(
          customControls: widget.custome,
          videoPlayerController: _videoPlayerController,
          autoPlay: false,
          looping: true,
          showOptions: widget.showOptions,
          allowPlaybackSpeedChanging: widget.showOptions,
          aspectRatio: 16 / 9,
          materialProgressColors: ChewieProgressColors(
              playedColor: Theme.of(context).colorScheme.primary,
              handleColor: Theme.of(context).colorScheme.primary),
        );
      });
    }).catchError((e) {
      setState(() {});
    });
  }

  @override
  void dispose() {
    _videoPlayerController.pause();
    _videoPlayerController.dispose();
    _chewieController?.dispose(); // Dispose of the ChewieController
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return _chewieController == null
        ? DefaultPlaceHolder(
            child: Container(
              width: MediaQuery.sizeOf(context).width,
              height: 200,
              decoration: BoxDecoration(
                  color: Colors.white, borderRadius: BorderRadius.circular(16)),
            ),
          )
        : AspectRatio(
            aspectRatio: _videoPlayerController.value.aspectRatio,
            child: Chewie(
              controller: _chewieController!,
            ),
          );
  }
}
