import 'package:flutter/material.dart';
import '../../services/call_session.dart';

/// Animated status dot + label reflecting the current [SessionState].
class StatusIndicator extends StatefulWidget {
  final SessionState state;

  const StatusIndicator({super.key, required this.state});

  @override
  State<StatusIndicator> createState() => _StatusIndicatorState();
}

class _StatusIndicatorState extends State<StatusIndicator>
    with SingleTickerProviderStateMixin {
  late final AnimationController _blink;

  @override
  void initState() {
    super.initState();
    _blink = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 600),
    )..repeat(reverse: true);
  }

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

  @override
  Widget build(BuildContext context) {
    final cfg = _config(widget.state);
    final shouldBlink = widget.state == SessionState.transmitting ||
        widget.state == SessionState.receiving;

    Widget dot = AnimatedBuilder(
      animation: _blink,
      builder: (_, __) {
        final opacity = shouldBlink ? (0.4 + 0.6 * _blink.value) : 1.0;
        return Opacity(
          opacity: opacity,
          child: Container(
            width: 14,
            height: 14,
            decoration: BoxDecoration(
              color: cfg.color,
              shape: BoxShape.circle,
              boxShadow: [
                BoxShadow(
                  color: cfg.color.withValues(alpha: 0.6),
                  blurRadius: 8,
                  spreadRadius: 2,
                ),
              ],
            ),
          ),
        );
      },
    );

    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        dot,
        const SizedBox(width: 8),
        Text(
          cfg.label,
          style: TextStyle(
            color: cfg.color,
            fontWeight: FontWeight.w600,
            fontSize: 13,
            letterSpacing: 1.2,
          ),
        ),
      ],
    );
  }

  static _StatusConfig _config(SessionState s) {
    switch (s) {
      case SessionState.noKey:
        return const _StatusConfig(Colors.grey, 'NO KEY');
      case SessionState.keyLoaded:
        return const _StatusConfig(Colors.blueAccent, 'KEY READY');
      case SessionState.inCall:
        return const _StatusConfig(Color(0xFF00C853), 'IN CALL');
      case SessionState.transmitting:
        return const _StatusConfig(Color(0xFFFF6D00), 'TRANSMITTING');
      case SessionState.receiving:
        return const _StatusConfig(Color(0xFF00B0FF), 'RECEIVING');
      case SessionState.error:
        return const _StatusConfig(Colors.red, 'ERROR');
    }
  }
}

class _StatusConfig {
  final Color  color;
  final String label;
  const _StatusConfig(this.color, this.label);
}
