import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart'; // Pour la lecture des vidéos

class StoryVideoPlayer extends StatefulWidget {
  final String mediaUrl;

  const StoryVideoPlayer({super.key, required this.mediaUrl});

  @override
  StoryVideoPlayerState createState() => StoryVideoPlayerState(); // Classe publique
}

class StoryVideoPlayerState extends State<StoryVideoPlayer> {
  VideoPlayerController? _videoPlayerController;
  bool _loadingError = false;

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

  void _initializeVideoPlayer() async {
    _videoPlayerController = VideoPlayerController.networkUrl(Uri.parse(widget.mediaUrl));

    try {
      await _videoPlayerController!.initialize();
      setState(() {
        _loadingError = false;
        _videoPlayerController!.play();
      });
    } catch (e) {
      setState(() {
        _loadingError = true;
      });
    }
  }

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

  @override
  Widget build(BuildContext context) {
    if (_loadingError) {
      return _buildRetryUI();
    } else if (_videoPlayerController != null && _videoPlayerController!.value.isInitialized) {
      return VideoPlayer(_videoPlayerController!);
    } else {
      return const Center(child: CircularProgressIndicator());
    }
  }

  Widget _buildRetryUI() {
    return Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          const Text('Problème de connexion ou de chargement', style: TextStyle(color: Colors.white)),
          const SizedBox(height: 20),
          ElevatedButton(
            onPressed: () {
              setState(() {
                _initializeVideoPlayer();
              });
            },
            child: const Text('Réessayer'),
          ),
        ],
      ),
    );
  }
}
