import 'dart:async';

import 'package:chewie/chewie.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hoshan/ui/widgets/components/video/play_btn_animation.dart';

class CustomControls extends StatefulWidget {
  const CustomControls({super.key});

  @override
  State<CustomControls> createState() => _CustomControlsState();
}

class _CustomControlsState extends State<CustomControls> {
  late ChewieController chewieController;
  bool isAnimating = false;
  double opacity = 1;
  Timer? _hideControlsTimer;
  ValueNotifier<Duration> position = ValueNotifier(Duration.zero);

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    chewieController = ChewieController.of(context);
    chewieController.videoPlayerController.addListener(
      () {
        position.value = chewieController.videoPlayerController.value.position;
      },
    );
  }

  void _startHideControlsTimer() {
    _hideControlsTimer?.cancel();
    _hideControlsTimer = Timer(const Duration(seconds: 3), () {
      setState(() {
        opacity = 0;
      });
    });
  }

  @override
  void dispose() {
    _hideControlsTimer?.cancel(); // Clean up the timer
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Directionality(
      textDirection: TextDirection.ltr,
      child: AnimatedOpacity(
        duration: const Duration(milliseconds: 400),
        opacity: opacity,
        child: InkWell(
          onTap: () {
            setState(() {
              opacity = 1;
            });
            _startHideControlsTimer(); // Restart the timer on tap
          },
          child: Stack(
            children: [
              Positioned(
                bottom: 0,
                left: 0,
                right: 0,
                child: Container(
                  padding: const EdgeInsets.only(bottom: 12),
                  decoration: const BoxDecoration(
                      gradient: LinearGradient(
                          begin: Alignment.bottomCenter,
                          end: Alignment.topCenter,
                          colors: [
                        Colors.black,
                        Colors.black26,
                        Color.fromARGB(10, 0, 0, 0)
                      ])),
                  child: Row(
                    children: [
                      // Positioned.fill(
                      //     child: Container(
                      //   decoration: BoxDecoration(
                      //       color: !chewieController.isPlaying
                      //           ? Colors.black.withOpacity(0.4)
                      //           : Colors.transparent),
                      // )),
                      _buildPlayPause(),

                      _buildProgressIndicator(),
                      _buildFullScreenToggle(),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildPlayPause() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 8.0),
      child: InkWell(
        onTap: () {
          setState(() {
            if (chewieController.isPlaying) {
              chewieController.pause();
              opacity = 1;
            } else {
              chewieController.play();
              opacity = 0;
            }

            isAnimating = true;
          });
          _startHideControlsTimer(); // Restart the timer on tap
        },
        child: PlayBtnAnimation(
          alwaysAnimate: true,
          isAnimating: isAnimating,
          onEnd: () => setState(
            () => isAnimating = false,
          ),
          child: Icon(
            chewieController.isPlaying
                ? CupertinoIcons.pause_fill
                : CupertinoIcons.play_fill,
            color: Colors.white,
            size: 24,
          ),
        ),
      ),
    );
  }

  Widget _buildProgressIndicator() {
    return Expanded(
      child: ValueListenableBuilder<Duration>(
        valueListenable: position,
        builder: (context, p, _) {
          Duration duration =
              chewieController.videoPlayerController.value.duration;

          return SliderTheme(
            data: SliderThemeData(
                trackHeight: 2,
                // thumbColor: Colors.transparent,
                overlayShape: SliderComponentShape.noOverlay,
                thumbShape: const RoundSliderThumbShape(
                    // elevation: 0,
                    // pressedElevation: 0,
                    enabledThumbRadius: 8)),
            child: Slider(
              min: 0,
              max: duration.inMilliseconds.toDouble(),
              value: p.inMilliseconds.toDouble(),
              onChanged: (value) async {
                await chewieController.pause();
                position.value = Duration(milliseconds: value.round());
                _startHideControlsTimer();
              },
              onChangeEnd: (value) async {
                await chewieController
                    .seekTo(Duration(milliseconds: value.round()));
                await chewieController.play();

                setState(() {});
              },
            ),
          );
        },
      ),
    );
  }

  Widget _buildFullScreenToggle() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 8.0),
      child: InkWell(
        onTap: () => setState(() {
          chewieController.toggleFullScreen();
          _startHideControlsTimer(); // Restart the timer on tap
        }),
        child: Icon(
          chewieController.isFullScreen
              ? Icons.fullscreen_exit
              : Icons.fullscreen,
          color: Colors.white,
          size: 30,
        ),
      ),
    );
  }
}
