import 'dart:async';

import 'package:flutter/material.dart';

import 'package:cached_video_player_plus/cached_video_player_plus.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import 'package:f0ckapp/models/mediaitem_model.dart';
import 'package:f0ckapp/widgets/videooverlay_widget.dart';
import 'package:f0ckapp/providers/media_provider.dart';

class VideoWidget extends ConsumerStatefulWidget {
  final MediaItem details;
  final bool isActive;
  final bool fullScreen;

  const VideoWidget({
    super.key,
    required this.details,
    required this.isActive,
    this.fullScreen = false,
  });

  @override
  ConsumerState<VideoWidget> createState() => _VideoWidgetState();
}

class _VideoWidgetState extends ConsumerState<VideoWidget> {
  late CachedVideoPlayerPlusController _controller;
  bool _showControls = false;
  Timer? _hideControlsTimer;

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

  Future<void> _initController() async {
    _controller = CachedVideoPlayerPlusController.networkUrl(
      Uri.parse(widget.details.mediaUrl),
    );
    await _controller.initialize();
    setState(() {});

    _controller.addListener(() => setState(() {}));

    if (widget.isActive) {
      _controller.play();
    }
    _controller.setLooping(true);

    final bool muted = ref.read(mediaProvider).muted;
    _controller.setVolume(muted ? 0.0 : 1.0);
  }

  @override
  void didUpdateWidget(covariant VideoWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.isActive != oldWidget.isActive) {
      if (widget.isActive) {
        _controller.play();
      } else {
        _controller.pause();
      }
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    _hideControlsTimer?.cancel();
    super.dispose();
  }

  void _onTap({bool ctrlButton = false}) {
    if (!ctrlButton) {
      setState(() => _showControls = !_showControls);
    }
    if (_showControls) {
      _hideControlsTimer?.cancel();
      _hideControlsTimer = Timer(const Duration(seconds: 2), () {
        setState(() => _showControls = false);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final bool muted = ref.watch(mediaProvider).muted;
    if (_controller.value.isInitialized &&
        _controller.value.volume != (muted ? 0.0 : 1.0)) {
      _controller.setVolume(muted ? 0.0 : 1.0);
    }

    bool isAudio = widget.details.mime.startsWith('audio');

    if (widget.fullScreen) {
      return Stack(
        children: [
          Center(
            child: AspectRatio(
              aspectRatio: _controller.value.isInitialized
                  ? _controller.value.aspectRatio
                  : 9 / 16,
              child: GestureDetector(
                onTap: _onTap,
                child: isAudio
                    ? CachedNetworkImage(
                        imageUrl: widget.details.coverUrl,
                        fit: BoxFit.cover,
                        placeholder: (context, url) =>
                            const CircularProgressIndicator(),
                        errorWidget: (context, url, error) => Image.asset(
                          'assets/images/music.webp',
                          fit: BoxFit.contain,
                          width: double.infinity,
                        ),
                      )
                    : _controller.value.isInitialized
                    ? CachedVideoPlayerPlus(_controller)
                    : const Center(child: CircularProgressIndicator()),
              ),
            ),
          ),
          if (_controller.value.isInitialized && _showControls)
            Positioned.fill(
              child: GestureDetector(
                onTap: _onTap,
                child: Container(
                  color: Colors.black.withValues(alpha: 0.5),
                  child: VideoControlsOverlay(
                    controller: _controller,
                    button: () => _onTap(ctrlButton: true),
                  ),
                ),
              ),
            ),
        ],
      );
    } else {
      return Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          AspectRatio(
            aspectRatio: _controller.value.isInitialized
                ? _controller.value.aspectRatio
                : 9 / 16,
            child: Stack(
              alignment: Alignment.topCenter,
              children: [
                GestureDetector(
                  onTap: _onTap,
                  child: isAudio
                      ? CachedNetworkImage(
                          imageUrl: widget.details.coverUrl,
                          fit: BoxFit.cover,
                          placeholder: (context, url) =>
                              const CircularProgressIndicator(),
                          errorWidget: (context, url, error) => Image.asset(
                            'assets/images/music.webp',
                            fit: BoxFit.contain,
                            width: double.infinity,
                          ),
                        )
                      : _controller.value.isInitialized
                      ? CachedVideoPlayerPlus(_controller)
                      : const Center(child: CircularProgressIndicator()),
                ),
                if (_controller.value.isInitialized && _showControls) ...[
                  IgnorePointer(
                    ignoring: true,
                    child: Container(
                      color: Colors.black.withValues(alpha: 0.5),
                      width: double.infinity,
                      height: double.infinity,
                    ),
                  ),
                  VideoControlsOverlay(
                    controller: _controller,
                    button: () => _onTap(ctrlButton: true),
                  ),
                ],
              ],
            ),
          ),
        ],
      );
    }
  }
}
