import 'dart:async';

import 'package:flutter/material.dart';

class AnimatedTime extends StatefulWidget {
  final Duration Function() callback;
  const AnimatedTime({super.key, required this.callback});

  @override
  State<AnimatedTime> createState() => _AnimatedTimeState();
}

class _AnimatedTimeState extends State<AnimatedTime> {
  Duration current = Duration.zero;
  late Timer timer;

  @override
  void initState() {
    super.initState();
    timer = Timer.periodic(const Duration(seconds: 1), (Timer t) => update());
    current = widget.callback();
  }

  void update() {
    setState(() {
      current = widget.callback();
    });
  }

  @override
  Widget build(BuildContext context) => Row(
    children: [
      const Text('Noch '),
      buildWidget(current.inDays),
      const Text(' Tage, '),
      buildWidget(
        current.inHours > 24
            ? current.inHours - current.inDays * 24
            : current.inHours,
      ),
      const Text(':'),
      buildWidget(
        current.inMinutes > 60
            ? current.inMinutes - current.inHours * 60
            : current.inMinutes,
      ),
      const Text(':'),
      buildWidget(
        current.inSeconds > 60
            ? current.inSeconds - current.inMinutes * 60
            : current.inSeconds,
      ),
    ],
  );

  Widget buildWidget(int value) => AnimatedSwitcher(
    duration: const Duration(milliseconds: 100),
    transitionBuilder: (child, animation) =>
        FadeTransition(opacity: animation, child: child),
    child: Text(
      '$value',
      key: ValueKey<int>(value),
      style: TextStyle(
        fontSize: 15,
        color: Theme.of(context).colorScheme.onSurface,
      ),
    ),
  );

  @override
  void dispose() {
    timer.cancel();
    super.dispose();
  }
}
