import 'package:flutter/material.dart';
import 'package:aves/remote/remote_sync_bus.dart';

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

  @override
  State<RemoteStatusIcon> createState() => _RemoteStatusIconState();
}

class _RemoteStatusIconState extends State<RemoteStatusIcon> with SingleTickerProviderStateMixin {
  late final AnimationController _blink = AnimationController(
    vsync: this,
    duration: const Duration(milliseconds: 700),
    lowerBound: 0.25,
    upperBound: 1.0,
  );

  @override
  void dispose() {
    _blink.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final bus = RemoteSyncBus.instance;

    return ValueListenableBuilder<RemoteSyncState>(
      valueListenable: bus.stateNotifier,
      builder: (context, st, _) {
        Color color;
        bool blinking = false;

        switch (st) {
          case RemoteSyncState.syncing:
            color = Colors.redAccent;
            blinking = true;
            break;
          case RemoteSyncState.upToDate:
            color = Colors.greenAccent;
            blinking = false;
            break;
          case RemoteSyncState.error:
            color = Colors.amberAccent;
            blinking = true;
            break;
          case RemoteSyncState.idle:
          default:
            // se vuoi "non aggiornato" rosso fisso:
            color = Colors.redAccent;
            blinking = false;
            break;
        }

        if (blinking) {
          if (!_blink.isAnimating) _blink.repeat(reverse: true);
        } else {
          if (_blink.isAnimating) _blink.stop();
          _blink.value = 1.0;
        }

        return FadeTransition(
          opacity: _blink,
          // icona "parabola" (puoi cambiare se vuoi)
          child: Icon(Icons.wifi_tethering_rounded, color: color),
        );
      },
    );
  }
}
