import 'package:flutter/material.dart';
import 'package:logging/logging.dart';
import 'package:media_kit/media_kit.dart';
import 'package:media_kit_video/media_kit_video.dart';

class MediaKitAvControl extends StatefulWidget {
  final String videoUrl;
  final double? width;
  final double? height;
  final Function()? onGoFullScreen;

  const MediaKitAvControl({
    super.key,
    required this.videoUrl,
    required this.width,
    required this.height,
    this.onGoFullScreen,
  });

  @override
  State<MediaKitAvControl> createState() => _MediaKitAvControlState();
}

class _MediaKitAvControlState extends State<MediaKitAvControl> {
  static final _logger = Logger('$MediaKitAvControl');
  final Player player = Player(
    configuration: const PlayerConfiguration(
      logLevel: MPVLogLevel.warn,
    ),
  );
  VideoController? controller;

  @override
  void initState() {
    super.initState();
    controller = VideoController(player);
    player.open(Media(widget.videoUrl), play: false);
  }

  @override
  void dispose() {
    Future.microtask(() async {
      await player.dispose();
    });
    super.dispose();
  }

  @override
  void deactivate() {
    player.pause();
    super.deactivate();
  }

  double? get height => widget.height == null ? null : widget.height! - 50;

  double? get width => widget.width;

  @override
  Widget build(BuildContext context) {
    _logger.finest('Building MediaKit Control for ${widget.videoUrl}');
    if (controller == null) {
      return Container(
        width: widget.width,
        height: widget.height,
        color: Colors.black12,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: const [
            CircularProgressIndicator(),
          ],
        ),
      );
    }

    return GestureDetector(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Expanded(
            child: Video(
              controller: controller!,
              width: width,
              height: height,
            ),
          ),
        ],
      ),
    );
  }
}
