import 'package:flutter/material.dart'; import '../theme.dart'; import '../db/dao/alarmas_dao.dart'; class AlarmasPage extends StatefulWidget { const AlarmasPage({Key? key}) : super(key: key); @override State createState() => _AlarmasPageState(); } class _AlarmasPageState extends State with SingleTickerProviderStateMixin { final _dao = AlarmasDao(); late final TabController _tab; List> _activas = []; List> _historial = []; bool _cargando = true; String? _filtroTipo; // null = todos static const _tipos = ['intrusion', 'humo', 'movimiento', 'acceso']; @override void initState() { super.initState(); _tab = TabController(length: 2, vsync: this); _cargar(); } @override void dispose() { _tab.dispose(); super.dispose(); } Future _cargar() async { setState(() => _cargando = true); try { final activas = await _dao.getActivasConZona(); final historial = await _dao.getHistorialConZona(); if (!mounted) return; setState(() { _activas = activas; _historial = historial; }); } catch (_) {} if (mounted) setState(() => _cargando = false); } // ── Helpers ────────────────────────────────────────────────────────────────── List> get _activasFiltradas { if (_filtroTipo == null) return _activas; return _activas.where((a) => a['tipo'] == _filtroTipo).toList(); } Color _sevColor(int sev) { if (sev >= 5) return AppColors.error; if (sev >= 4) return AppColors.tertiary; if (sev >= 3) return AppColors.secondary; if (sev >= 2) return AppColors.onSecondaryContainer; return AppColors.outline; } IconData _tipoIcon(String tipo) { switch (tipo) { case 'intrusion': return Icons.warning_amber_rounded; case 'humo': return Icons.local_fire_department; case 'movimiento': return Icons.directions_run; case 'acceso': return Icons.lock_open; default: return Icons.notifications; } } String _tipoLabel(String tipo) { switch (tipo) { case 'intrusion': return 'INTRUSIÓN'; case 'humo': return 'HUMO'; case 'movimiento': return 'MOVIMIENTO'; case 'acceso': return 'ACCESO'; default: return tipo.toUpperCase(); } } String _formatTs(String iso) { try { final dt = DateTime.parse(iso).toLocal(); final d = dt.day.toString().padLeft(2, '0'); final mo = dt.month.toString().padLeft(2, '0'); final h = dt.hour.toString().padLeft(2, '0'); final m = dt.minute.toString().padLeft(2, '0'); return '$d/$mo $h:$m'; } catch (_) { return iso; } } Color _estadoColor(String estado) { switch (estado) { case 'resuelta': return AppColors.primary; case 'silenciada': return AppColors.outline; default: return AppColors.error; } } String _estadoLabel(String estado) { switch (estado) { case 'resuelta': return 'RESUELTA'; case 'silenciada': return 'SILENCIADA'; default: return estado.toUpperCase(); } } // ── Acciones ───────────────────────────────────────────────────────────────── Future _responder(Map a) async { final notasCtrl = TextEditingController(); final ok = await showDialog( context: context, builder: (_) => AlertDialog( backgroundColor: AppColors.surfaceHigh, title: Text('Responder alarma', style: appHeadline(size: 16)), content: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( '${_tipoLabel(a['tipo'] as String)} · ${a['zona_nombre'] ?? 'Sin zona'}', style: appLabel(size: 12), ), const SizedBox(height: 16), TextField( controller: notasCtrl, style: appLabel(size: 13, color: AppColors.onSurface), maxLines: 3, decoration: InputDecoration( hintText: 'Notas de resolución (opcional)', hintStyle: appLabel(size: 12), filled: true, fillColor: AppColors.surfaceLowest, border: OutlineInputBorder( borderRadius: BorderRadius.circular(8), borderSide: BorderSide.none, ), ), ), ], ), actions: [ TextButton( onPressed: () => Navigator.pop(context, false), child: Text('Cancelar', style: appLabel(size: 13, color: AppColors.outline)), ), ElevatedButton( onPressed: () => Navigator.pop(context, true), style: ElevatedButton.styleFrom( primary: AppColors.primary, onPrimary: AppColors.surfaceLowest, elevation: 0, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), ), child: Text('Confirmar', style: appLabel(size: 13, weight: FontWeight.bold, color: AppColors.surfaceLowest)), ), ], ), ); if (ok == true && mounted) { await _dao.resolver(a['id'] as int, 1, notas: notasCtrl.text.trim().isEmpty ? null : notasCtrl.text.trim()); _cargar(); ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Text('Alarma resuelta', style: appLabel(size: 13, color: AppColors.surfaceLowest)), backgroundColor: AppColors.primary, behavior: SnackBarBehavior.floating, )); } } Future _silenciar(Map a) async { final ok = await showDialog( context: context, builder: (_) => AlertDialog( backgroundColor: AppColors.surfaceHigh, title: Text('Silenciar alarma', style: appHeadline(size: 16)), content: Text( 'La alarma se marcará como silenciada.\n${_tipoLabel(a['tipo'] as String)} · ${a['zona_nombre'] ?? ''}', style: appLabel(size: 13, color: AppColors.onSurface), ), actions: [ TextButton( onPressed: () => Navigator.pop(context, false), child: Text('Cancelar', style: appLabel(size: 13, color: AppColors.outline)), ), ElevatedButton( onPressed: () => Navigator.pop(context, true), style: ElevatedButton.styleFrom( primary: AppColors.onSurfaceVariant, onPrimary: AppColors.surfaceLowest, elevation: 0, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), ), child: Text('Silenciar', style: appLabel(size: 13, weight: FontWeight.bold, color: AppColors.surfaceLowest)), ), ], ), ); if (ok == true && mounted) { await _dao.silenciar(a['id'] as int); _cargar(); ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Text('Alarma silenciada', style: appLabel(size: 13, color: AppColors.onSurface)), backgroundColor: AppColors.surfaceHighest, behavior: SnackBarBehavior.floating, )); } } Future _escalar(Map a) async { final sevActual = a['severidad'] as int; if (sevActual >= 5) { ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Text('Ya está en nivel máximo (5)', style: appLabel(size: 13, color: AppColors.onSurface)), backgroundColor: AppColors.surfaceHighest, behavior: SnackBarBehavior.floating, )); return; } final ok = await showDialog( context: context, builder: (_) => AlertDialog( backgroundColor: AppColors.surfaceHigh, title: Text('Escalar alarma', style: appHeadline(size: 16)), content: Text( 'La severidad subirá de NIVEL $sevActual → NIVEL ${sevActual + 1}.\n' 'Se notificará a la central cuando se sincronice.', style: appLabel(size: 13, color: AppColors.onSurface), ), actions: [ TextButton( onPressed: () => Navigator.pop(context, false), child: Text('Cancelar', style: appLabel(size: 13, color: AppColors.outline)), ), ElevatedButton( onPressed: () => Navigator.pop(context, true), style: ElevatedButton.styleFrom( primary: AppColors.tertiary, onPrimary: AppColors.surfaceLowest, elevation: 0, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), ), child: Text('Escalar', style: appLabel(size: 13, weight: FontWeight.bold, color: AppColors.surfaceLowest)), ), ], ), ); if (ok == true && mounted) { await _dao.escalar(a['id'] as int); _cargar(); ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Text('Alarma escalada a nivel ${sevActual + 1}', style: appLabel(size: 13, color: AppColors.surfaceLowest)), backgroundColor: AppColors.tertiary, behavior: SnackBarBehavior.floating, )); } } // ── Build ───────────────────────────────────────────────────────────────────── @override Widget build(BuildContext context) { return Scaffold( backgroundColor: AppColors.surfaceLowest, appBar: AppBar( backgroundColor: AppColors.surfaceLow, elevation: 0, leading: IconButton( icon: const Icon(Icons.arrow_back_ios_new, size: 18, color: AppColors.onSurface), onPressed: () => Navigator.pop(context), ), title: Text('ALARMAS', style: appHeadline(size: 14, spacing: 2.0)), bottom: TabBar( controller: _tab, labelStyle: appLabel(size: 12, weight: FontWeight.bold, spacing: 1.5), unselectedLabelStyle: appLabel(size: 12, spacing: 1.5), labelColor: AppColors.primary, unselectedLabelColor: AppColors.outline, indicatorColor: AppColors.primary, indicatorWeight: 2, tabs: const [ Tab(text: 'ACTIVAS'), Tab(text: 'HISTORIAL'), ], ), ), body: TabBarView( controller: _tab, children: [ _tabActivas(), _tabHistorial(), ], ), ); } // ── Tab Activas ─────────────────────────────────────────────────────────────── Widget _tabActivas() { final lista = _activasFiltradas; return RefreshIndicator( onRefresh: _cargar, color: AppColors.primary, backgroundColor: AppColors.surfaceHigh, child: CustomScrollView( physics: const AlwaysScrollableScrollPhysics(), primary: false, slivers: [ SliverToBoxAdapter(child: _filtroChips()), if (_cargando) const SliverFillRemaining( child: Center(child: CircularProgressIndicator( strokeWidth: 2, color: AppColors.primary)), ) else if (lista.isEmpty) SliverFillRemaining(child: _emptyState( icon: Icons.shield_outlined, titulo: 'Sin alarmas activas', sub: 'Todos los sectores en estado normal', color: AppColors.primary, )) else ...[ SliverToBoxAdapter( child: Padding( padding: const EdgeInsets.fromLTRB(20, 4, 20, 12), child: Text( '${lista.length} alarma${lista.length == 1 ? '' : 's'} activa${lista.length == 1 ? '' : 's'}', style: appLabel(size: 12, color: AppColors.outline), ), ), ), SliverList( delegate: SliverChildBuilderDelegate( (_, i) => Padding( padding: EdgeInsets.fromLTRB(16, 0, 16, i == lista.length - 1 ? 24 : 12), child: _alarmaCard(lista[i]), ), childCount: lista.length, ), ), ], ], ), ); } Widget _filtroChips() { return SingleChildScrollView( scrollDirection: Axis.horizontal, padding: const EdgeInsets.fromLTRB(16, 16, 16, 8), child: Row( children: [ _chip('Todos', null), ..._tipos.map((t) => _chip(_tipoLabel(t), t)), ], ), ); } Widget _chip(String label, String? tipo) { final selected = _filtroTipo == tipo; return Padding( padding: const EdgeInsets.only(right: 8), child: GestureDetector( onTap: () => setState(() => _filtroTipo = tipo), child: AnimatedContainer( duration: const Duration(milliseconds: 200), padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 7), decoration: BoxDecoration( color: selected ? AppColors.primaryContainer : AppColors.surfaceHigh, borderRadius: BorderRadius.circular(20), border: Border.all( color: selected ? AppColors.primary : AppColors.outlineVariant, width: 1, ), ), child: Text( label, style: appLabel( size: 11, weight: selected ? FontWeight.bold : FontWeight.normal, color: selected ? AppColors.primary : AppColors.onSurfaceVariant, spacing: 1.0, ), ), ), ), ); } Widget _alarmaCard(Map a) { final sev = a['severidad'] as int; final tipo = a['tipo'] as String; final zona = a['zona_nombre'] as String? ?? 'Zona desconocida'; final codigo = a['zona_codigo'] as String? ?? ''; final ts = _formatTs(a['timestamp'] as String); final color = _sevColor(sev); return ClipRRect( borderRadius: BorderRadius.circular(12), child: IntrinsicHeight( child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Container(width: 5, color: color), Expanded( child: Container( color: AppColors.surfaceHigh, padding: const EdgeInsets.all(16), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ // Cabecera Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( padding: const EdgeInsets.all(8), decoration: BoxDecoration( color: color.withOpacity(0.12), borderRadius: BorderRadius.circular(8), ), child: Icon(_tipoIcon(tipo), color: color, size: 18), ), const SizedBox(width: 12), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( _tipoLabel(tipo), style: appLabel(size: 10, weight: FontWeight.bold, color: color, spacing: 1.5), ), const SizedBox(height: 2), Text(zona, style: appHeadline(size: 15)), if (codigo.isNotEmpty) Text(codigo, style: appLabel(size: 11)), ], ), ), // Badge severidad Container( padding: const EdgeInsets.symmetric( horizontal: 10, vertical: 5), decoration: BoxDecoration( color: color.withOpacity(0.15), borderRadius: BorderRadius.circular(6), ), child: Text( 'N$sev', style: appLabel(size: 12, weight: FontWeight.bold, color: color, spacing: 0.5), ), ), ], ), const SizedBox(height: 10), // Timestamp Row(children: [ const Icon(Icons.schedule, size: 13, color: AppColors.outline), const SizedBox(width: 5), Text(ts, style: appLabel(size: 11)), ]), const SizedBox(height: 14), // Botones de acción Row(children: [ _accionBtn('RESPONDER', AppColors.primary, () => _responder(a)), const SizedBox(width: 8), _accionBtn('SILENCIAR', AppColors.onSurfaceVariant, () => _silenciar(a)), const SizedBox(width: 8), _accionBtn('ESCALAR', sev >= 5 ? AppColors.outlineVariant : AppColors.tertiary, sev >= 5 ? null : () => _escalar(a)), ]), ], ), ), ), ], ), ), ); } Widget _accionBtn(String label, Color color, VoidCallback? onTap) => Expanded( child: GestureDetector( onTap: onTap, child: Container( padding: const EdgeInsets.symmetric(vertical: 8), decoration: BoxDecoration( color: onTap != null ? color.withOpacity(0.12) : AppColors.surfaceLowest, borderRadius: BorderRadius.circular(7), border: Border.all( color: onTap != null ? color.withOpacity(0.3) : AppColors.outlineVariant, ), ), child: Text( label, textAlign: TextAlign.center, style: appLabel(size: 10, weight: FontWeight.bold, color: onTap != null ? color : AppColors.outlineVariant, spacing: 1.0), ), ), ), ); // ── Tab Historial ───────────────────────────────────────────────────────────── Widget _tabHistorial() { return RefreshIndicator( onRefresh: _cargar, color: AppColors.primary, backgroundColor: AppColors.surfaceHigh, child: _cargando ? const Center(child: CircularProgressIndicator( strokeWidth: 2, color: AppColors.primary)) : _historial.isEmpty ? _emptyState( icon: Icons.history, titulo: 'Sin historial', sub: 'Las alarmas resueltas y silenciadas aparecerán aquí', color: AppColors.outline, ) : ListView.separated( physics: const AlwaysScrollableScrollPhysics(), primary: false, padding: const EdgeInsets.fromLTRB(16, 16, 16, 24), itemCount: _historial.length, separatorBuilder: (_, __) => const SizedBox(height: 8), itemBuilder: (_, i) => _historialItem(_historial[i]), ), ); } Widget _historialItem(Map a) { final sev = a['severidad'] as int; final tipo = a['tipo'] as String; final zona = a['zona_nombre'] as String? ?? 'Zona desconocida'; final ts = _formatTs(a['timestamp'] as String); final estado = a['estado'] as String; final notas = a['notas'] as String?; final sevColor = _sevColor(sev); final estadoC = _estadoColor(estado); return Container( padding: const EdgeInsets.all(14), decoration: BoxDecoration( color: AppColors.surfaceLow, borderRadius: BorderRadius.circular(10), ), child: Row( children: [ Icon(_tipoIcon(tipo), color: sevColor, size: 18), const SizedBox(width: 12), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row(children: [ Text(_tipoLabel(tipo), style: appLabel(size: 10, weight: FontWeight.bold, color: sevColor, spacing: 1.0)), const SizedBox(width: 6), Text('·', style: appLabel(size: 10, color: AppColors.outlineVariant)), const SizedBox(width: 6), Text('N$sev', style: appLabel(size: 10, color: sevColor)), ]), const SizedBox(height: 2), Text(zona, style: appHeadline(size: 13)), if (notas != null && notas.isNotEmpty) Padding( padding: const EdgeInsets.only(top: 2), child: Text(notas, style: appLabel(size: 11), maxLines: 1, overflow: TextOverflow.ellipsis), ), const SizedBox(height: 4), Text(ts, style: appLabel(size: 11, color: AppColors.outline)), ], ), ), const SizedBox(width: 8), Container( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), decoration: BoxDecoration( color: estadoC.withOpacity(0.12), borderRadius: BorderRadius.circular(5), ), child: Text(_estadoLabel(estado), style: appLabel(size: 9, weight: FontWeight.bold, color: estadoC, spacing: 0.8)), ), ], ), ); } // ── Empty state ─────────────────────────────────────────────────────────────── Widget _emptyState({ required IconData icon, required String titulo, required String sub, required Color color, }) => Center( child: Padding( padding: const EdgeInsets.all(40), child: Column( mainAxisSize: MainAxisSize.min, children: [ Icon(icon, color: color, size: 36), const SizedBox(height: 12), Text(titulo, style: appHeadline(size: 15, color: color)), const SizedBox(height: 6), Text(sub, textAlign: TextAlign.center, style: appLabel(size: 12, color: AppColors.outline)), ], ), ), ); }