// lib/features/guardian_dashboard/guardian_activity_log_screen.dart
// ignore_for_file: use_build_context_synchronously

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:intl/intl.dart';

import '../../../app/injection_container.dart';
import '../../../core/network/api_client.dart';

Dio get _api => sl<ApiClient>().dio;

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

  @override
  State<GuardianActivityLogScreen> createState() =>
      _GuardianActivityLogScreenState();
}

class _GuardianActivityLogScreenState extends State<GuardianActivityLogScreen> {
  List<_LogItem> _items = [];
  List<_LogItem> _filtered = [];
  bool _loading = true;
  String? _error;
  String _selectedFilter = 'ALL';
  bool _needsPairing = false;

  static const _filters = [
    'ALL',
    'WALKGUIDE',
    'SOS',
    'AUTH',
    'OBSTACLE',
    'LOCATION',
  ];

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

  Future<void> _load() async {
    setState(() {
      _loading = true;
      _error = null;
      _needsPairing = false;
    });
    try {
      // Cek pairing dulu
      final paired = await _hasActivePairing();
      if (!paired) {
        setState(() {
          _needsPairing = true;
          _loading = false;
        });
        return;
      }

      final res = await _api.get('/guardian/activity-logs', queryParameters: {
        'size': 50,
        'page': 0
      }).timeout(const Duration(seconds: 10));

      // Response bisa berupa list langsung atau paged {content: [...]}
      final data = res.data['data'];
      List<dynamic> list;
      if (data is List) {
        list = data;
      } else if (data is Map && data['content'] is List) {
        list = data['content'] as List;
      } else {
        list = [];
      }

      final items = list
          .whereType<Map>()
          .map((e) => _LogItem.fromJson(Map<String, dynamic>.from(e)))
          .toList();

      setState(() {
        _items = items;
        _applyFilter(_selectedFilter);
        _loading = false;
      });
    } on DioException catch (e) {
      setState(() {
        _error = e.response?.data?['message']?.toString() ??
            'Gagal memuat activity log.';
        _loading = false;
      });
    } catch (e) {
      setState(() {
        _error = 'Timeout / error: $e';
        _loading = false;
      });
    }
  }

  Future<bool> _hasActivePairing() async {
    try {
      final res = await _api
          .get('/shared/pairing/status')
          .timeout(const Duration(seconds: 5));
      final data = res.data['data'];
      if (data is Map) return data['status'] == 'ACTIVE';
    } catch (_) {}
    return false;
  }

  void _applyFilter(String filter) {
    _selectedFilter = filter;
    if (filter == 'ALL') {
      _filtered = List.from(_items);
    } else {
      _filtered = _items.where((item) {
        switch (filter) {
          case 'WALKGUIDE':
            return item.logType.contains('WALKGUIDE');
          case 'SOS':
            return item.logType.contains('SOS');
          case 'AUTH':
            return item.logType == 'LOGIN' ||
                item.logType == 'LOGOUT' ||
                item.logType == 'APP_OPEN' ||
                item.logType == 'APP_CLOSE';
          case 'OBSTACLE':
            return item.logType.contains('OBSTACLE');
          case 'LOCATION':
            return item.logType.contains('LOCATION') ||
                item.logType.contains('GEOFENCE');
          default:
            return true;
        }
      }).toList();
    }
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // ── Header ──────────────────────────────────────────────────────
            Row(
              children: [
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        'User Logs',
                        style: GoogleFonts.outfit(
                          fontSize: 22,
                          fontWeight: FontWeight.w800,
                          color: const Color(0xFF0F172A),
                        ),
                      ),
                      Text(
                        _needsPairing
                            ? 'Pairing dulu untuk melihat log'
                            : '${_items.length} aktivitas tercatat',
                        style: GoogleFonts.inter(
                          fontSize: 13,
                          color: const Color(0xFF64748B),
                        ),
                      ),
                    ],
                  ),
                ),
                IconButton(
                  onPressed: _load,
                  icon: const Icon(Icons.refresh_rounded),
                  tooltip: 'Refresh',
                  color: const Color(0xFF64748B),
                ),
              ],
            ),
            const SizedBox(height: 12),

            // ── Filter chips ─────────────────────────────────────────────────
            if (!_needsPairing && !_loading && _error == null)
              SizedBox(
                height: 36,
                child: ListView.separated(
                  scrollDirection: Axis.horizontal,
                  itemCount: _filters.length,
                  separatorBuilder: (_, __) => const SizedBox(width: 8),
                  itemBuilder: (_, i) {
                    final f = _filters[i];
                    final selected = _selectedFilter == f;
                    return FilterChip(
                      label: Text(f),
                      selected: selected,
                      onSelected: (_) => setState(() => _applyFilter(f)),
                      selectedColor:
                          const Color(0xFF1A56DB).withValues(alpha: 0.12),
                      checkmarkColor: const Color(0xFF1A56DB),
                      labelStyle: GoogleFonts.inter(
                        color: selected
                            ? const Color(0xFF1A56DB)
                            : const Color(0xFF64748B),
                        fontWeight:
                            selected ? FontWeight.w700 : FontWeight.normal,
                        fontSize: 12,
                      ),
                      padding: const EdgeInsets.symmetric(horizontal: 4),
                      side: BorderSide(
                        color: selected
                            ? const Color(0xFF1A56DB)
                            : const Color(0xFFE2E8F0),
                      ),
                    );
                  },
                ),
              ),

            if (!_needsPairing && !_loading && _error == null)
              const SizedBox(height: 16),

            // ── Body ─────────────────────────────────────────────────────────
            Expanded(
              child: _loading
                  ? const Center(child: CircularProgressIndicator())
                  : _needsPairing
                      ? _buildNoPairingPanel()
                      : _error != null
                          ? _buildErrorPanel()
                          : _filtered.isEmpty
                              ? _buildEmptyPanel()
                              : RefreshIndicator(
                                  onRefresh: _load,
                                  color: const Color(0xFF1A56DB),
                                  child: ListView.builder(
                                    itemCount: _filtered.length,
                                    itemBuilder: (ctx, i) =>
                                        _LogCard(item: _filtered[i]),
                                  ),
                                ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildNoPairingPanel() {
    return Center(
      child: Container(
        padding: const EdgeInsets.all(24),
        margin: const EdgeInsets.symmetric(horizontal: 16),
        decoration: BoxDecoration(
          color: const Color(0xFFFFFBEB),
          borderRadius: BorderRadius.circular(16),
          border: Border.all(color: const Color(0xFFFDE68A)),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Icon(Icons.link_off, color: Color(0xFFD97706), size: 52),
            const SizedBox(height: 14),
            Text(
              'Belum Pairing',
              style: GoogleFonts.outfit(
                fontSize: 18,
                fontWeight: FontWeight.w700,
                color: const Color(0xFF92400E),
              ),
            ),
            const SizedBox(height: 8),
            Text(
              'Hubungkan akun Guardian dengan User terlebih dahulu untuk melihat log aktivitas.',
              style: GoogleFonts.inter(
                fontSize: 13,
                color: const Color(0xFF92400E),
              ),
              textAlign: TextAlign.center,
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildErrorPanel() {
    return Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          const Icon(Icons.wifi_off, size: 52, color: Color(0xFF94A3B8)),
          const SizedBox(height: 14),
          Text(
            _error!,
            textAlign: TextAlign.center,
            style:
                GoogleFonts.inter(fontSize: 13, color: const Color(0xFF64748B)),
          ),
          const SizedBox(height: 18),
          FilledButton.icon(
            onPressed: _load,
            icon: const Icon(Icons.refresh),
            label: const Text('Coba lagi'),
            style: FilledButton.styleFrom(
                backgroundColor: const Color(0xFF1A56DB)),
          ),
        ],
      ),
    );
  }

  Widget _buildEmptyPanel() {
    return Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          const Icon(Icons.history, size: 64, color: Color(0xFF94A3B8)),
          const SizedBox(height: 14),
          Text(
            _selectedFilter == 'ALL'
                ? 'Belum ada aktivitas'
                : 'Tidak ada aktivitas "$_selectedFilter"',
            style: GoogleFonts.inter(
              fontSize: 15,
              fontWeight: FontWeight.w600,
              color: const Color(0xFF94A3B8),
            ),
          ),
        ],
      ),
    );
  }
}

// ─────────────────────────────────────────────────────────────────────────────
//  DATA MODEL
// ─────────────────────────────────────────────────────────────────────────────

class _LogItem {
  final int id;
  final String logType;
  final String? description;
  final DateTime createdAt;

  const _LogItem({
    required this.id,
    required this.logType,
    this.description,
    required this.createdAt,
  });

  factory _LogItem.fromJson(Map<String, dynamic> j) => _LogItem(
        id: (j['id'] as num?)?.toInt() ?? 0,
        logType: j['logType']?.toString() ?? 'UNKNOWN',
        description: j['description']?.toString(),
        createdAt:
            DateTime.tryParse(j['createdAt']?.toString() ?? '')?.toLocal() ??
                DateTime.now(),
      );
}

// ─────────────────────────────────────────────────────────────────────────────
//  LOG CARD
// ─────────────────────────────────────────────────────────────────────────────

class _LogCard extends StatelessWidget {
  final _LogItem item;
  const _LogCard({required this.item});

  @override
  Widget build(BuildContext context) {
    final meta = _logMeta(item.logType);
    return Padding(
      padding: const EdgeInsets.only(bottom: 8),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Timeline dot + connector line
          Column(
            children: [
              Container(
                width: 38,
                height: 38,
                decoration: BoxDecoration(
                  color: meta.color.withValues(alpha: 0.12),
                  shape: BoxShape.circle,
                ),
                child: Icon(meta.icon, color: meta.color, size: 18),
              ),
              Container(
                width: 1.5,
                height: 22,
                color: const Color(0xFFE2E8F0),
              ),
            ],
          ),
          const SizedBox(width: 12),
          // Content
          Expanded(
            child: Padding(
              padding: const EdgeInsets.only(top: 6),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Expanded(
                        child: Text(
                          meta.label,
                          style: GoogleFonts.inter(
                            fontWeight: FontWeight.w700,
                            color: meta.color,
                            fontSize: 13,
                          ),
                        ),
                      ),
                      Text(
                        _formatTime(item.createdAt),
                        style: GoogleFonts.jetBrainsMono(
                          color: const Color(0xFF94A3B8),
                          fontSize: 11,
                        ),
                      ),
                    ],
                  ),
                  if (item.description != null && item.description!.isNotEmpty)
                    Padding(
                      padding: const EdgeInsets.only(top: 3),
                      child: Text(
                        item.description!,
                        style: GoogleFonts.inter(
                          fontSize: 12,
                          color: const Color(0xFF64748B),
                        ),
                      ),
                    ),
                  const SizedBox(height: 14),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  String _formatTime(DateTime dt) {
    final now = DateTime.now();
    if (dt.day == now.day && dt.month == now.month && dt.year == now.year) {
      return DateFormat('HH:mm').format(dt);
    }
    return DateFormat('dd MMM HH:mm').format(dt);
  }
}

// ─────────────────────────────────────────────────────────────────────────────
//  LOG METADATA
// ─────────────────────────────────────────────────────────────────────────────

class _LogMeta {
  final IconData icon;
  final Color color;
  final String label;
  const _LogMeta(
      {required this.icon, required this.color, required this.label});
}

_LogMeta _logMeta(String logType) {
  switch (logType.toUpperCase()) {
    case 'LOGIN':
      return const _LogMeta(
          icon: Icons.login, color: Color(0xFF16A34A), label: 'Login');
    case 'LOGOUT':
      return const _LogMeta(
          icon: Icons.logout, color: Color(0xFF94A3B8), label: 'Logout');
    case 'APP_OPEN':
      return const _LogMeta(
          icon: Icons.open_in_new,
          color: Color(0xFF1A56DB),
          label: 'App Dibuka');
    case 'APP_CLOSE':
      return const _LogMeta(
          icon: Icons.close, color: Color(0xFF94A3B8), label: 'App Ditutup');
    case 'WALKGUIDE_START':
      return const _LogMeta(
          icon: Icons.directions_walk,
          color: Color(0xFF1A56DB),
          label: 'WalkGuide Mulai');
    case 'WALKGUIDE_STOP':
      return const _LogMeta(
          icon: Icons.stop_circle,
          color: Color(0xFF94A3B8),
          label: 'WalkGuide Berhenti');
    case 'OBSTACLE_DETECTED':
      return const _LogMeta(
          icon: Icons.warning_amber,
          color: Color(0xFFD97706),
          label: 'Obstacle Terdeteksi');
    case 'SOS_TRIGGERED':
      return const _LogMeta(
          icon: Icons.sos, color: Color(0xFFDC2626), label: 'SOS Terkirim');
    case 'SOS_ACKNOWLEDGED':
      return const _LogMeta(
          icon: Icons.check_circle,
          color: Color(0xFF16A34A),
          label: 'SOS Diakui Guardian');
    case 'CALL_INITIATED':
      return const _LogMeta(
          icon: Icons.call,
          color: Color(0xFF16A34A),
          label: 'Panggilan Dimulai');
    case 'CALL_ENDED':
      return const _LogMeta(
          icon: Icons.call_end,
          color: Color(0xFF94A3B8),
          label: 'Panggilan Selesai');
    case 'LOCATION_UPDATE':
      return const _LogMeta(
          icon: Icons.location_on,
          color: Color(0xFF1A56DB),
          label: 'Lokasi Diperbarui');
    case 'GEOFENCE_EXIT':
      return const _LogMeta(
          icon: Icons.fence,
          color: Color(0xFFDC2626),
          label: 'Keluar Area Aman');
    case 'GEOFENCE_ENTER':
      return const _LogMeta(
          icon: Icons.home, color: Color(0xFF16A34A), label: 'Masuk Area Aman');
    default:
      return _LogMeta(
          icon: Icons.circle_outlined,
          color: const Color(0xFF94A3B8),
          label: logType);
  }
}
