import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/last_heard_item.dart';
import '../models/user_info.dart';
import '../services/authentication_manager.dart';
import '../services/lastheard_websocket_client.dart';
import '../widgets/user_header.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;
  UserInfo? _userInfo;
  String? _firstRadioId;

  @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 userInfo = authManager.userInfo;
    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(() {
      _userInfo = userInfo;
      _firstRadioId = devices.isNotEmpty ? devices.first.id.toString() : null;
      _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(() {
            _items.add(item);

            // Sort by timestamp, most recent first
            _items.sort((a, b) => b.start.compareTo(a.start));

            // 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 + 1,
      itemBuilder: (context, index) {
        if (index == 0) {
          return UserHeader(userInfo: _userInfo, radioId: _firstRadioId);
        }
        final item = _items[index - 1];
        return _LastHeardItemTile(item: item);
      },
    );
  }
}

class _LastHeardItemTile extends StatelessWidget {
  final LastHeardItem item;

  const _LastHeardItemTile({required this.item});

  @override
  Widget build(BuildContext context) {
    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            const Icon(
              Icons.arrow_forward,
              color: Colors.green,
              size: 20,
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Row(
                    children: [
                      Text(
                        item.destinationDisplayName,
                        style: const TextStyle(fontWeight: FontWeight.bold),
                      ),
                      if (item.durationDisplay.isNotEmpty) ...[
                        const SizedBox(width: 8),
                        Text(
                          item.durationDisplay,
                          style: TextStyle(fontSize: 14, color: Colors.grey[600]),
                        ),
                      ],
                      const Spacer(),
                      Text(
                        item.timeAgo,
                        style: TextStyle(fontSize: 12, color: Colors.grey[600]),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
