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

class VideoPlayerWidget extends StatefulWidget {
  final String videoUrl;

  const VideoPlayerWidget({
    super.key,
    required this.videoUrl,
  });

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

class VideoPlayerWidgetState extends State<VideoPlayerWidget> {
  VideoPlayerController? _videoController;
  YoutubePlayerController? _youtubeController;
  FlickManager? _flickManager;
  bool _isLoading = true;
  String? _error;
  String? _youtubeId;
  bool _isDisposed = false;

  @override
  void initState() {
    super.initState();
    _youtubeId = _extractYoutubeId(widget.videoUrl);

    if (_youtubeId != null) {
      _youtubeController = YoutubePlayerController(
        initialVideoId: _youtubeId!,
        flags: const YoutubePlayerFlags(
          mute: false,
          autoPlay: false,
          disableDragSeek: true,
          loop: false,
          enableCaption: false,
          hideThumbnail: false,
        ),
      );
      if (!_isDisposed) {
        setState(() {
          _isLoading = false;
        });
      }
    } else {
      _initializeVideo();
    }
  }

  Future<void> _initializeVideo() async {
    try {
      await _initializeRegularVideo();
    } catch (e) {
      if (!_isDisposed) {
        setState(() {
          _error = "Error initializing video player: $e";
          _isLoading = false;
        });
      }
    }
  }

  String? _extractYoutubeId(String url) {
    try {
      if (url.contains('youtube.com/watch?v=')) {
        return url.split('watch?v=')[1].split('&')[0];
      }
      if (url.contains('youtube.com/embed/')) {
        return url.split('youtube.com/embed/')[1].split('?')[0];
      }
      if (url.contains('youtu.be/')) {
        return url.split('youtu.be/')[1].split('?')[0];
      }
      return null;
    } catch (e) {
      print('Error extracting YouTube ID: $e');
      return null;
    }
  }

  String _getPlayableUrl(String url) {
    if (url.contains('drive.google.com')) {
      if (url.contains('/view')) {
        url = url.replaceAll('/view', '');
      }
      final regex = RegExp(r'/d/([a-zA-Z0-9-_]+)');
      final match = regex.firstMatch(url);
      if (match != null) {
        final fileId = match.group(1);
        return 'https://drive.google.com/uc?export=download&id=$fileId';
      }
    }
    return url;
  }

  Future<void> _initializeRegularVideo() async {
    try {
      final playableUrl = _getPlayableUrl(widget.videoUrl);
      _videoController = VideoPlayerController.networkUrl(
        Uri.parse(playableUrl),
      );

      await _videoController!.initialize();

      if (!_isDisposed) {
        _flickManager = FlickManager(
          videoPlayerController: _videoController!,
          autoPlay: false,
        );

        setState(() {
          _isLoading = false;
        });
      }
    } catch (e) {
      if (!_isDisposed) {
        setState(() {
          _error = "Error initializing video player: $e";
          _isLoading = false;
        });
      }
    }
  }

  @override
  void dispose() {
    _isDisposed = true;
    _videoController?.dispose();
    _youtubeController?.dispose();
    _flickManager?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (_error != null) {
      return _buildErrorContainer();
    }

    return ClipRRect(
      borderRadius: BorderRadius.circular(16),
      child: AspectRatio(
        aspectRatio: 16 / 9,
        child:
            _youtubeId != null ? _buildYoutubePlayer() : _buildRegularVideo(),
      ),
    );
  }

  Widget _buildErrorContainer() {
    return ClipRRect(
      borderRadius: BorderRadius.circular(16),
      child: AspectRatio(
        aspectRatio: 16 / 9,
        child: Container(
          color: Colors.black,
          child: Center(
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Text(
                _error!,
                style: const TextStyle(color: Colors.white),
                textAlign: TextAlign.center,
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildYoutubePlayer() {
    if (_youtubeController == null) {
      return Container(
        color: Colors.black,
        child: const Center(
          child: CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
          ),
        ),
      );
    }

    return YoutubePlayer(
      controller: _youtubeController!,
      showVideoProgressIndicator: true,
      progressIndicatorColor: Colors.red,
      progressColors: const ProgressBarColors(
        playedColor: Colors.red,
        handleColor: Colors.redAccent,
      ),
      onReady: () {
        print('YouTube Player Ready');
      },
    );
  }

  Widget _buildRegularVideo() {
    if (_isLoading) {
      return Container(
        color: Colors.black,
        child: const Center(
          child: CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
          ),
        ),
      );
    }

    if (_flickManager != null) {
      return FlickVideoPlayer(flickManager: _flickManager!);
    }

    return const SizedBox.shrink();
  }

  void stopAndResetVideo() {
    if (_youtubeController != null) {
      _youtubeController!.seekTo(Duration.zero);
      _youtubeController!.pause();
    } else if (_videoController != null) {
      _videoController!.seekTo(Duration.zero);
      _videoController!.pause();
    }
  }
}
