import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:gz_video_player/video_brightness_style.dart';

class BrightnessWidget extends StatefulWidget {
  final ValueListenable<double> brightness;
  final VideoBrightnessStyle videoBrightnessStyle;

  BrightnessWidget({
    super.key,
    required this.brightness,
    VideoBrightnessStyle? videoBrightnessStyle,
  }) : videoBrightnessStyle = videoBrightnessStyle ?? VideoBrightnessStyle();

  @override
  State<BrightnessWidget> createState() => _BrightnessWidgetState();
}

class _BrightnessWidgetState extends State<BrightnessWidget> {
  ValueListenable<double> get brightness => widget.brightness;

  VideoBrightnessStyle get videoBrightnessStyle => widget.videoBrightnessStyle;

  Timer? timer;
  bool hidden = true;

  @override
  void initState() {
    super.initState();
    brightness.addListener(listener);
  }

  @override
  Widget build(BuildContext context) {
    return Align(
      child: ValueListenableBuilder(
        valueListenable: brightness,
        builder: (BuildContext context, double value, Widget? child) {
          int brightness = (value * 100).toInt();
          return Offstage(
            offstage: hidden,
            child: Container(
              width: videoBrightnessStyle.size.width,
              height: videoBrightnessStyle.size.height,
              decoration: BoxDecoration(
                color: videoBrightnessStyle.backgroundColor,
                borderRadius: videoBrightnessStyle.borderRadius,
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  videoBrightnessStyle.brightnessIcon,
                  Text(
                    '${brightness.toString()}%',
                    style: videoBrightnessStyle.textStyle,
                  )
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  @override
  void dispose() {
    brightness.removeListener(listener);
    timer?.cancel();
    super.dispose();
  }

  void listener() {
    if (hidden) {
      hidden = false;
      setState(() {});
    }
    timer?.cancel();
    timer = Timer(const Duration(milliseconds: 250), () {
      hidden = true;
      setState(() {});
      timer?.cancel();
    });
  }
}
