import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../core/api/api_client_provider.dart';

class ActiveSessionsScreen extends ConsumerStatefulWidget {
  const ActiveSessionsScreen({super.key});

  @override
  ConsumerState<ActiveSessionsScreen> createState() => _ActiveSessionsScreenState();
}

class _ActiveSessionsScreenState extends ConsumerState<ActiveSessionsScreen> {
  List<Map<String, dynamic>> _sessions = [];
  bool _loading = true;

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

  Future<void> _loadSessions() async {
    try {
      final apiClient = ref.read(apiClientProvider);
      final response = await apiClient.get('/api/mitra/chat-requests/sessions/active');
      setState(() {
        _sessions = List<Map<String, dynamic>>.from(response['data'] as List);
        _loading = false;
      });
    } catch (_) {
      setState(() => _loading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Sesi Aktif')),
      body: _loading
          ? const Center(child: CircularProgressIndicator())
          : _sessions.isEmpty
              ? const Center(child: Text('Tidak ada sesi aktif.'))
              : ListView.builder(
                  itemCount: _sessions.length,
                  itemBuilder: (context, index) {
                    final session = _sessions[index];
                    final customerName = session['customer_display_name'] as String? ?? 'Customer';
                    return ListTile(
                      leading: const Icon(Icons.chat),
                      title: Text(customerName),
                      subtitle: Text('Status: ${session['status']}'),
                      trailing: const Icon(Icons.chevron_right),
                      onTap: () => context.push(
                        '/chat/session/${session['id']}',
                        extra: {'customerName': customerName},
                      ),
                    );
                  },
                ),
    );
  }
}
