import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/last_heard_item.dart';
import '../services/authentication_manager.dart';
import '../services/lastheard_websocket_client.dart';

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

  @override
  State<LastHeardView> createState() => _LastHeardViewState();
}

class _LastHeardViewState extends State<LastHeardView> {
  LastHeardWebSocketClient? _wsClient;
  StreamSubscription<Map<String, dynamic>>? _wsSubscription;
  final List<LastHeardItem> _items = [];
  static const int _maxItems = 200;
  bool _isConnecting = true;

  @override
  void initState() {
    super.initState();
    _connectWebSocket();
  }

  @override
  void dispose() {
    _wsSubscription?.cancel();
    _wsClient?.dispose();
    super.dispose();
  }

  Future<void> _connectWebSocket() async {
    setState(() {
      _isConnecting = true;
    });

    final authManager = context.read<AuthenticationManager>();
    final devices = await authManager.getDevices();
    final radioIds = devices.map((d) => d.id).toList();

    _wsClient = LastHeardWebSocketClient(radioIds: radioIds);
    await _wsClient!.connect();

    _wsSubscription = _wsClient!.messageStream.listen((message) {
      if (message['event'] == 'mqtt' && message['data'] is Map) {
        _handleMqttMessage(message['data'] as Map<String, dynamic>);
      }
    });

    setState(() {
      _isConnecting = false;
    });
  }

  void _handleMqttMessage(Map<String, dynamic> data) {
    try {
      final topic = data['topic'] as String?;
      if (topic == 'LH-Startup') {
        final payloadStr = data['payload'] as String?;
        if (payloadStr != null) {
          final payload = jsonDecode(payloadStr) as Map<String, dynamic>;
          final item = LastHeardItem.fromJson(payload);

          // Filter out items without a callsign
          if (item.sourceCall.isEmpty) {
            return;
          }

          setState(() {
            // Add to the beginning of the list
            _items.insert(0, item);

            // Keep only the latest 200 items
            if (_items.length > _maxItems) {
              _items.removeRange(_maxItems, _items.length);
            }
          });
        }
      }
    } catch (e) {
      debugPrint('Error handling MQTT message: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Last Activity'),
      ),
      body: _buildBody(),
    );
  }

  Widget _buildBody() {
    if (_isConnecting) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(),
            SizedBox(height: 16),
            Text('Connecting to Last Activity...'),
          ],
        ),
      );
    }

    if (_items.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.history,
              size: 64,
              color: Colors.grey[400],
            ),
            const SizedBox(height: 16),
            Text(
              'No activity yet',
              style: Theme.of(context).textTheme.titleLarge,
            ),
            const SizedBox(height: 8),
            Text(
              'Waiting for Last Activity data...',
              style: TextStyle(color: Colors.grey[600]),
            ),
          ],
        ),
      );
    }

    return ListView.builder(
      itemCount: _items.length,
      itemBuilder: (context, index) {
        final item = _items[index];
        return _LastHeardItemTile(item: item);
      },
    );
  }
}

class _LastHeardItemTile extends StatelessWidget {
  final LastHeardItem item;

  const _LastHeardItemTile({required this.item});

  Color _getEventColor(BuildContext context) {
    switch (item.event) {
      case 'Session-Start':
        return Colors.green;
      case 'Session-Stop':
        return Colors.red;
      default:
        return Theme.of(context).colorScheme.primary;
    }
  }

  IconData _getEventIcon() {
    switch (item.event) {
      case 'Session-Start':
        return Icons.phone_in_talk;
      case 'Session-Stop':
        return Icons.call_end;
      default:
        return Icons.settings_input_antenna;
    }
  }

  @override
  Widget build(BuildContext context) {
    final eventColor = _getEventColor(context);

    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      child: ListTile(
        leading: CircleAvatar(
          backgroundColor: eventColor.withValues(alpha: 0.2),
          child: Icon(
            _getEventIcon(),
            color: eventColor,
            size: 20,
          ),
        ),
        title: Row(
          children: [
            Expanded(
              child: Text(
                item.displayName,
                style: const TextStyle(fontWeight: FontWeight.bold),
              ),
            ),
            if (item.rssi != null)
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                decoration: BoxDecoration(
                  color: Colors.grey[200],
                  borderRadius: BorderRadius.circular(4),
                ),
                child: Text(
                  '${item.rssi} dBm',
                  style: TextStyle(
                    fontSize: 11,
                    color: Colors.grey[700],
                  ),
                ),
              ),
          ],
        ),
        subtitle: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(height: 4),
            Row(
              children: [
                Icon(Icons.arrow_forward, size: 12, color: Colors.grey[600]),
                const SizedBox(width: 4),
                Expanded(
                  child: Text(
                    item.destinationDisplayName,
                    style: TextStyle(color: Colors.grey[700]),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 2),
            Row(
              children: [
                Container(
                  padding:
                      const EdgeInsets.symmetric(horizontal: 4, vertical: 1),
                  decoration: BoxDecoration(
                    color: eventColor.withValues(alpha: 0.1),
                    borderRadius: BorderRadius.circular(3),
                  ),
                  child: Text(
                    'TS${item.slot}',
                    style: TextStyle(
                      fontSize: 10,
                      color: eventColor,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                const SizedBox(width: 6),
                Text(
                  item.linkTypeName,
                  style: TextStyle(fontSize: 11, color: Colors.grey[600]),
                ),
                const SizedBox(width: 6),
                Text(
                  '•',
                  style: TextStyle(color: Colors.grey[400]),
                ),
                const SizedBox(width: 6),
                Text(
                  item.timeAgo,
                  style: TextStyle(fontSize: 11, color: Colors.grey[600]),
                ),
              ],
            ),
          ],
        ),
        isThreeLine: true,
      ),
    );
  }
}
