// ignore_for_file: deprecated_member_use

import 'package:chewie/chewie.dart';
import 'package:didvan/config/theme_data.dart';
import 'package:didvan/services/network/request.dart';
import 'package:didvan/views/widgets/shimmer_placeholder.dart';

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

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

  @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 {
    final videoUrl = '${widget.src}?accessToken=${RequestService.token}';
    print('🎬 ChatVideoPlayer - Initializing video...');
    print('🎬 ChatVideoPlayer - URL: $videoUrl');
    
    _videoPlayerController = VideoPlayerController.network(videoUrl);

    await _videoPlayerController.initialize().then((_) {
      print('🎬 ChatVideoPlayer - Video initialized successfully!');
      print('🎬 ChatVideoPlayer - Duration: ${_videoPlayerController.value.duration}');
      print('🎬 ChatVideoPlayer - Size: ${_videoPlayerController.value.size}');
      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.title,
              handleColor: Theme.of(context).colorScheme.title),
        );
      });
    }).catchError((e) {
      print('🎬 ChatVideoPlayer - ERROR: $e');
      setState(() {});
    });
  }

  @override
  void dispose() {
    _videoPlayerController.pause();
    _videoPlayerController.dispose();
    _chewieController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return _chewieController == null
        ? ShimmerPlaceholder(
            width: MediaQuery.sizeOf(context).width,
            height: 200,
          )
        : AspectRatio(
            aspectRatio: _videoPlayerController.value.aspectRatio,
            child: Chewie(
              controller: _chewieController!,
            ),
          );
  }
}
