import 'dart:async'; import 'package:flutter/material.dart'; import '../theme.dart'; import '../db/dao/cache_alarmas_dao.dart'; import '../db/dao/cache_clientes_dao.dart'; import '../db/dao/incidentes_dao.dart'; class DashboardPage extends StatefulWidget { const DashboardPage({Key? key}) : super(key: key); @override State createState() => _DashboardPageState(); } class _DashboardPageState extends State { final _alarmasDao = CacheAlarmasDao(); final _clientesDao = CacheClientesDao(); final _incidentesDao = IncidentesDao(); List> _alarmas = []; List> _clientes = []; List> _incidentes = []; int _totalClientes = 0; int _totalActivas = 0; int _totalCriticas = 0; int _totalPendientes = 0; bool _cargando = true; DateTime? _ultimaActualizacion; Timer? _timer; @override void initState() { super.initState(); _cargar(); _timer = Timer.periodic(const Duration(seconds: 30), (_) => _cargar()); } @override void dispose() { _timer?.cancel(); super.dispose(); } Future _cargar() async { if (!mounted) return; setState(() => _cargando = true); final results = await Future.wait([ _clientesDao.getTodos(), _alarmasDao.getActivas(), _incidentesDao.getRecientes(limit: 8), _incidentesDao.getPendientes(), _alarmasDao.contarActivas(), _alarmasDao.contarCriticas(), _clientesDao.contarActivos(), ]); if (!mounted) return; setState(() { _clientes = List>.from(results[0] as List); _alarmas = List>.from(results[1] as List); _incidentes = List>.from(results[2] as List); _totalPendientes = (results[3] as List).length; _totalActivas = results[4] as int; _totalCriticas = results[5] as int; _totalClientes = results[6] as int; _cargando = false; _ultimaActualizacion = DateTime.now(); }); } // ── Helpers ────────────────────────────────────────────────────────────────── String _timeAgo(String? iso) { if (iso == null) return ''; final dt = DateTime.tryParse(iso); if (dt == null) return ''; final diff = DateTime.now().difference(dt); if (diff.inSeconds < 60) return 'ahora'; if (diff.inMinutes < 60) return 'hace ${diff.inMinutes} min'; if (diff.inHours < 24) return 'hace ${diff.inHours} h'; return 'hace ${diff.inDays} d'; } String _horaCorta(DateTime dt) { final h = dt.hour.toString().padLeft(2, '0'); final m = dt.minute.toString().padLeft(2, '0'); final s = dt.second.toString().padLeft(2, '0'); return '$h:$m:$s'; } Color _colorSeveridad(int sev) { if (sev >= 4) return AppColors.alarmaActiva; if (sev == 3) return AppColors.clienteAlerta; return AppColors.alarmaSilenciada; } String _labelSeveridad(int sev) { if (sev >= 5) return 'MAX'; if (sev == 4) return 'CRIT'; if (sev == 3) return 'ALTA'; if (sev == 2) return 'MED'; return 'BAJA'; } Color _colorEstadoCliente(String? estado) { if (estado == 'critico') return AppColors.clienteCritico; if (estado == 'alerta') return AppColors.clienteAlerta; return AppColors.clienteOk; } // ── Build ──────────────────────────────────────────────────────────────────── @override Widget build(BuildContext context) { return SingleChildScrollView( primary: false, padding: const EdgeInsets.fromLTRB(28, 24, 28, 32), child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ _headerRow(), const SizedBox(height: 24), _statCards(), const SizedBox(height: 24), IntrinsicHeight( child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded(flex: 3, child: _alarmasSection()), const SizedBox(width: 16), Expanded(flex: 2, child: _clientesSection()), ]), ), const SizedBox(height: 16), _incidentesSection(), ]), ); } // ── Header ─────────────────────────────────────────────────────────────────── Widget _headerRow() => Row(children: [ Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ Text('Dashboard', style: appHeadline(size: 22, weight: FontWeight.w800)), const SizedBox(height: 2), Text( _ultimaActualizacion != null ? 'Actualizado a las ${_horaCorta(_ultimaActualizacion!)}' : 'Cargando…', style: appLabel(size: 12, color: AppColors.outline), ), ]), const Spacer(), if (_cargando) const SizedBox( width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 2, color: AppColors.primary), ) else IconButton( tooltip: 'Actualizar ahora', icon: const Icon(Icons.refresh, color: AppColors.outline, size: 20), onPressed: _cargar, ), ]); // ── Stat cards ─────────────────────────────────────────────────────────────── Widget _statCards() => Row(children: [ Expanded(child: _statCard( icono: Icons.business, color: AppColors.primary, valor: _totalClientes, label: 'Clientes activos', )), const SizedBox(width: 12), Expanded(child: _statCard( icono: Icons.notifications_active, color: AppColors.clienteAlerta, valor: _totalActivas, label: 'Alarmas activas', )), const SizedBox(width: 12), Expanded(child: _statCard( icono: Icons.warning_amber_rounded, color: AppColors.alarmaActiva, valor: _totalCriticas, label: 'Críticas (sev ≥4)', highlight: _totalCriticas > 0, )), const SizedBox(width: 12), Expanded(child: _statCard( icono: Icons.assignment_late_outlined, color: AppColors.secondary, valor: _totalPendientes, label: 'Incidentes pend.', )), ]); Widget _statCard({ required IconData icono, required Color color, required int valor, required String label, bool highlight = false, }) => Container( padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 18), decoration: BoxDecoration( color: highlight ? color.withOpacity(0.12) : AppColors.surfaceLow, borderRadius: BorderRadius.circular(12), border: Border.all( color: highlight ? color.withOpacity(0.4) : AppColors.outlineVariant, ), ), child: Row(children: [ Container( width: 40, height: 40, decoration: BoxDecoration( color: color.withOpacity(0.15), borderRadius: BorderRadius.circular(10), ), child: Icon(icono, color: color, size: 20), ), const SizedBox(width: 14), Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( '$valor', style: appHeadline( size: 26, weight: FontWeight.w800, color: highlight ? color : AppColors.onSurface), ), Text(label, style: appLabel(size: 11, color: AppColors.outline)), ]), ]), ); // ── Alarmas activas ────────────────────────────────────────────────────────── Widget _alarmasSection() => _card( title: 'Alarmas activas', icono: Icons.notifications_active_outlined, badge: _totalActivas > 0 ? '$_totalActivas' : null, badgeColor: _totalCriticas > 0 ? AppColors.alarmaActiva : AppColors.clienteAlerta, child: _alarmas.isEmpty ? _emptyState('Sin alarmas activas', Icons.notifications_none) : Column( children: _alarmas.take(12).map(_alarmaRow).toList(), ), ); Widget _alarmaRow(Map a) { final sev = (a['severidad'] as int?) ?? 1; final color = _colorSeveridad(sev); final label = _labelSeveridad(sev); return Padding( padding: const EdgeInsets.symmetric(vertical: 5), child: Row(children: [ // Badge severidad Container( width: 42, padding: const EdgeInsets.symmetric(vertical: 3), decoration: BoxDecoration( color: color.withOpacity(0.15), borderRadius: BorderRadius.circular(6), border: Border.all(color: color.withOpacity(0.3)), ), child: Center( child: Text(label, style: appLabel(size: 10, weight: FontWeight.bold, color: color)), ), ), const SizedBox(width: 10), // Contenido Expanded( child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( a['tipo'] as String? ?? '—', style: appLabel(size: 12, weight: FontWeight.w600, color: AppColors.onSurface), maxLines: 1, overflow: TextOverflow.ellipsis, ), Row(children: [ if (a['cliente_nombre'] != null) Text( a['cliente_nombre'] as String, style: appLabel(size: 11, color: AppColors.primary), ), if (a['zona_nombre'] != null) ...[ Text(' · ', style: appLabel(size: 11, color: AppColors.outline)), Text( a['zona_nombre'] as String, style: appLabel(size: 11, color: AppColors.onSurfaceVariant), ), ], ]), ]), ), const SizedBox(width: 8), Text( _timeAgo(a['timestamp'] as String?), style: appLabel(size: 11, color: AppColors.outline), ), ]), ); } // ── Clientes ───────────────────────────────────────────────────────────────── Widget _clientesSection() => _card( title: 'Estado de clientes', icono: Icons.business_outlined, badge: _totalClientes > 0 ? '$_totalClientes' : null, badgeColor: AppColors.primary, child: _clientes.isEmpty ? _emptyState('Sin clientes en caché', Icons.business_outlined) : Column( children: _clientes.take(10).map(_clienteRow).toList(), ), ); Widget _clienteRow(Map c) { final estado = c['estado'] as String? ?? 'normal'; final color = _colorEstadoCliente(estado); final criticas = (c['alarmas_criticas'] as int?) ?? 0; final activas = (c['alarmas_activas'] as int?) ?? 0; return Padding( padding: const EdgeInsets.symmetric(vertical: 5), child: Row(children: [ Container( width: 8, height: 8, decoration: BoxDecoration(shape: BoxShape.circle, color: color), ), const SizedBox(width: 10), Expanded( child: Text( c['nombre'] as String? ?? '—', style: appLabel( size: 12, weight: FontWeight.w500, color: criticas > 0 ? AppColors.onSurface : AppColors.onSurfaceVariant, ), maxLines: 1, overflow: TextOverflow.ellipsis, ), ), const SizedBox(width: 8), if (criticas > 0) _pillCount('$criticas', AppColors.alarmaActiva) else if (activas > 0) _pillCount('$activas', AppColors.clienteAlerta) else Text('OK', style: appLabel(size: 11, color: AppColors.clienteOk)), ]), ); } Widget _pillCount(String text, Color color) => Container( padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 2), decoration: BoxDecoration( color: color.withOpacity(0.15), borderRadius: BorderRadius.circular(20), ), child: Text(text, style: appLabel(size: 11, weight: FontWeight.bold, color: color)), ); // ── Incidentes recientes ───────────────────────────────────────────────────── Widget _incidentesSection() => _card( title: 'Últimos incidentes', icono: Icons.assignment_outlined, child: _incidentes.isEmpty ? _emptyState('Sin incidentes registrados', Icons.assignment_outlined) : Column(children: [ _incidenteHeader(), const Divider(color: AppColors.outlineVariant, height: 12), ..._incidentes.map(_incidenteRow), ]), ); Widget _incidenteHeader() => Padding( padding: const EdgeInsets.only(bottom: 4), child: Row(children: [ Expanded(flex: 2, child: Text('Tipo', style: appLabel(size: 11, color: AppColors.outline))), Expanded(flex: 2, child: Text('Cliente', style: appLabel(size: 11, color: AppColors.outline))), Expanded(flex: 2, child: Text('Operador', style: appLabel(size: 11, color: AppColors.outline))), SizedBox(width: 80, child: Text('Cuándo', style: appLabel(size: 11, color: AppColors.outline))), SizedBox(width: 70, child: Text('Estado', style: appLabel(size: 11, color: AppColors.outline))), ]), ); Widget _incidenteRow(Map inc) { final resuelto = (inc['resuelto'] as int?) == 1; return Padding( padding: const EdgeInsets.symmetric(vertical: 5), child: Row(children: [ Expanded( flex: 2, child: Text( inc['tipo'] as String? ?? '—', style: appLabel(size: 12, weight: FontWeight.w500, color: AppColors.onSurface), maxLines: 1, overflow: TextOverflow.ellipsis, ), ), Expanded( flex: 2, child: Text( inc['cliente_nombre'] as String? ?? '—', style: appLabel(size: 12, color: AppColors.primary), maxLines: 1, overflow: TextOverflow.ellipsis, ), ), Expanded( flex: 2, child: Text( inc['operador'] as String? ?? '—', style: appLabel(size: 12, color: AppColors.onSurfaceVariant), maxLines: 1, overflow: TextOverflow.ellipsis, ), ), SizedBox( width: 80, child: Text( _timeAgo(inc['timestamp'] as String?), style: appLabel(size: 11, color: AppColors.outline), ), ), SizedBox( width: 70, child: Container( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), decoration: BoxDecoration( color: resuelto ? AppColors.clienteOk.withOpacity(0.12) : AppColors.clienteAlerta.withOpacity(0.12), borderRadius: BorderRadius.circular(20), ), child: Text( resuelto ? 'Resuelto' : 'Pendiente', style: appLabel( size: 10, weight: FontWeight.w600, color: resuelto ? AppColors.clienteOk : AppColors.clienteAlerta, ), ), ), ), ]), ); } // ── Shared widgets ─────────────────────────────────────────────────────────── Widget _card({ required String title, required IconData icono, required Widget child, String? badge, Color badgeColor = AppColors.primary, }) => Container( padding: const EdgeInsets.all(20), decoration: BoxDecoration( color: AppColors.surfaceLow, borderRadius: BorderRadius.circular(12), border: Border.all(color: AppColors.outlineVariant), ), child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ Row(children: [ Icon(icono, size: 16, color: AppColors.outline), const SizedBox(width: 8), Text(title, style: appHeadline(size: 13, weight: FontWeight.w700)), if (badge != null) ...[ const SizedBox(width: 8), Container( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), decoration: BoxDecoration( color: badgeColor.withOpacity(0.15), borderRadius: BorderRadius.circular(20), ), child: Text(badge, style: appLabel(size: 11, weight: FontWeight.bold, color: badgeColor)), ), ], ]), const SizedBox(height: 14), child, ]), ); Widget _emptyState(String texto, IconData icono) => Padding( padding: const EdgeInsets.symmetric(vertical: 24), child: Center( child: Column(mainAxisSize: MainAxisSize.min, children: [ Icon(icono, size: 32, color: AppColors.outlineVariant), const SizedBox(height: 10), Text(texto, style: appLabel(size: 12, color: AppColors.outline)), const SizedBox(height: 4), Text('Esperando sincronización con Centinel', style: appLabel(size: 11, color: AppColors.outlineVariant)), ]), ), ); }