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';
import '../../../core/chat/widgets/sensitivity_badge.dart';
import '../../../core/constants.dart';

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

  @override
  ConsumerState<MitraChatHistoryScreen> createState() => _MitraChatHistoryScreenState();
}

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

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

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Riwayat Chat')),
      body: _loading
          ? const Center(child: CircularProgressIndicator())
          : _sessions.isEmpty
              ? const Center(child: Text('Belum ada riwayat chat'))
              : ListView.builder(
                  itemCount: _sessions.length,
                  itemBuilder: (context, index) {
                    final s = _sessions[index];
                    final sessionId = s['id'] as String;
                    final customerName = s['customer_display_name'] as String? ?? 'Customer';
                    final status = s['status'] as String?;
                    final isClosing = status == 'closing';
                    final endedAt = s['ended_at'] != null
                        ? DateTime.parse(s['ended_at'] as String).toLocal()
                        : null;
                    final duration = s['duration_minutes'] as int?;
                    final closureMsg = s['mitra_closure_message'] as String?;

                    final topic = TopicSensitivity.fromString(s['topic_sensitivity'] as String?);

                    return ListTile(
                      leading: const CircleAvatar(child: Icon(Icons.person)),
                      title: Row(
                        children: [
                          Flexible(child: Text(customerName, overflow: TextOverflow.ellipsis)),
                          if (topic == TopicSensitivity.sensitive) ...[
                            const SizedBox(width: 8),
                            SensitivityBadge(sensitivity: topic, fontSize: 10),
                          ],
                          if (isClosing) ...[
                            const SizedBox(width: 8),
                            const _OutstandingClosureBadge(),
                          ],
                        ],
                      ),
                      subtitle: Text([
                        if (endedAt != null) '${endedAt.day}/${endedAt.month}/${endedAt.year}',
                        if (duration != null) '$duration menit',
                        if (closureMsg != null) '"$closureMsg"',
                      ].join(' - ')),
                      trailing: const Icon(Icons.chevron_right),
                      onTap: () => isClosing
                          ? context.push('/chat/session/$sessionId', extra: customerName)
                          : context.push('/chat/history/$sessionId'),
                    );
                  },
                ),
    );
  }
}

class _OutstandingClosureBadge extends StatelessWidget {
  const _OutstandingClosureBadge();

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
      decoration: BoxDecoration(
        color: Colors.amber.shade100,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.amber.shade700, width: 0.5),
      ),
      child: Text(
        'Belum ditutup',
        style: TextStyle(
          fontSize: 10,
          color: Colors.amber.shade900,
          fontWeight: FontWeight.w600,
        ),
      ),
    );
  }
}
