import 'package:flutter/material.dart'; import '../theme.dart'; import '../db/dao/accesos_dao.dart'; import '../db/dao/usuarios_dao.dart'; import '../models/usuario.dart'; import 'registrar_usuario_page.dart'; class ControlAccesoPage extends StatefulWidget { const ControlAccesoPage({Key? key}) : super(key: key); @override State createState() => _ControlAccesoPageState(); } class _ControlAccesoPageState extends State { bool _lobbyBloqueado = true; bool _muelleBloqueado = false; bool _serverBloqueado = true; final _dao = AccesosDao(); final _usuariosDao = UsuariosDao(); List> _accesos = []; List _usuarios = []; bool _cargando = true; @override void initState() { super.initState(); _cargar(); } Future _cargar() async { setState(() => _cargando = true); try { final results = await Future.wait([ _dao.getRecientesConDetalle(limit: 20), _usuariosDao.getActivos(), ]); if (!mounted) return; setState(() { _accesos = results[0] as List>; _usuarios = results[1] as List; }); } catch (_) {} if (mounted) setState(() => _cargando = false); } void _abrirRegistro() { Navigator.push( context, MaterialPageRoute( fullscreenDialog: true, builder: (_) => const RegistrarUsuarioPage(), ), ).then((ok) { if (ok == true) _cargar(); }); } String _horaCorta(String iso) { try { final dt = DateTime.parse(iso).toLocal(); return '${dt.hour.toString().padLeft(2, '0')}:${dt.minute.toString().padLeft(2, '0')}'; } catch (_) { return '—'; } } String _metodoLabel(String metodo) { switch (metodo) { case 'remoto': return 'Apertura Remota'; case 'biometrico':return 'Biométrico'; default: return 'PIN'; } } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.transparent, floatingActionButton: FloatingActionButton.extended( onPressed: _abrirRegistro, backgroundColor: AppColors.primary, foregroundColor: AppColors.primaryContainer, icon: const Icon(Icons.person_add_alt_1, size: 20), label: Text('Registrar Usuario', style: appLabel( size: 13, weight: FontWeight.bold, color: AppColors.primaryContainer)), ), body: RefreshIndicator( onRefresh: _cargar, color: AppColors.primary, child: SingleChildScrollView( physics: const AlwaysScrollableScrollPhysics(), primary: false, padding: const EdgeInsets.fromLTRB(24, 24, 24, 96), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ _encabezado(), const SizedBox(height: 32), _gridEntradas(), const SizedBox(height: 40), _usuariosRegistrados(), const SizedBox(height: 40), _registroAcceso(), const SizedBox(height: 24), _snapshotCamara(), ], ), ), ), ); } // ── Encabezado ────────────────────────────────────────────────────────────── Widget _encabezado() => Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row(children: [ Container( width: 8, height: 8, decoration: const BoxDecoration( shape: BoxShape.circle, color: AppColors.primary), ), const SizedBox(width: 8), Text('SISTEMA ACTIVO', style: appLabel( size: 10, weight: FontWeight.bold, color: AppColors.primary, spacing: 2.0)), ]), const SizedBox(height: 4), Text('CONTROL DE ACCESO', style: appHeadline(size: 28, weight: FontWeight.w800)), ], ); // ── Grid de entradas ──────────────────────────────────────────────────────── Widget _gridEntradas() => Column(children: [ _cardLobbyPrincipal(), const SizedBox(height: 16), Row(children: [ Expanded(child: _cardMuelleCarga()), const SizedBox(width: 16), Expanded(child: _cardCentrosDatos()), ]), ]); Widget _cardLobbyPrincipal() => ClipRRect( borderRadius: BorderRadius.circular(12), child: IntrinsicHeight( child: Row(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Container(width: 4, color: AppColors.primary), Expanded( child: Container( color: AppColors.surfaceHigh, padding: const EdgeInsets.all(20), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: [ Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text('Entrada 01', style: appLabel(size: 10, spacing: 2.0)), const SizedBox(height: 4), Text('Lobby Principal', style: appHeadline(size: 17)), ]), _badgeEstado(_lobbyBloqueado), ], ), const SizedBox(height: 20), SizedBox( width: double.infinity, child: ElevatedButton.icon( onPressed: () => setState(() => _lobbyBloqueado = !_lobbyBloqueado), icon: Icon( _lobbyBloqueado ? Icons.lock_open : Icons.lock, size: 16), label: Text( _lobbyBloqueado ? 'DESBLOQUEO REMOTO' : 'BLOQUEAR PUERTA', style: appLabel( size: 13, weight: FontWeight.bold, color: AppColors.primaryContainer)), style: ElevatedButton.styleFrom( // Compatibilidad Flutter 3+: uso de backgroundColor y foregroundColor backgroundColor: AppColors.primary, foregroundColor: AppColors.primaryContainer, padding: const EdgeInsets.symmetric(vertical: 14), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(8)), elevation: 0, ), ), ), ], ), ), ), ]), ), ); Widget _cardMuelleCarga() => ClipRRect( borderRadius: BorderRadius.circular(12), child: IntrinsicHeight( child: Row(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Container(width: 4, color: AppColors.tertiary), Expanded( child: Container( color: AppColors.surfaceLow, padding: const EdgeInsets.all(16), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text('Puerta 04', style: appLabel(size: 10, spacing: 2.0)), const SizedBox(height: 4), Text('Muelle de Carga', style: appHeadline(size: 14)), const SizedBox(height: 12), _badgeEstado(_muelleBloqueado), const SizedBox(height: 12), SizedBox( width: double.infinity, child: ElevatedButton( onPressed: () => setState( () => _muelleBloqueado = !_muelleBloqueado), style: ElevatedButton.styleFrom( // Compatibilidad Flutter 3+: uso de backgroundColor y foregroundColor backgroundColor: AppColors.surfaceHighest, foregroundColor: AppColors.onSurface, padding: const EdgeInsets.symmetric(vertical: 10), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(8)), elevation: 0, ), child: Text( _muelleBloqueado ? 'DESBLOQUEAR' : 'ASEGURAR PUERTA', style: appLabel( size: 11, weight: FontWeight.bold, color: AppColors.onSurface)), ), ), ], ), ), ), ]), ), ); Widget _cardCentrosDatos() => ClipRRect( borderRadius: BorderRadius.circular(12), child: IntrinsicHeight( child: Row(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Container(width: 4, color: AppColors.primary), Expanded( child: Container( color: AppColors.surfaceLow, padding: const EdgeInsets.all(16), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text('Seguro 01', style: appLabel(size: 10, spacing: 2.0)), const SizedBox(height: 4), Text('Centro de Datos', style: appHeadline(size: 14)), const SizedBox(height: 12), _badgeEstado(_serverBloqueado), const SizedBox(height: 12), SizedBox( width: double.infinity, child: ElevatedButton( onPressed: () => setState( () => _serverBloqueado = !_serverBloqueado), style: ElevatedButton.styleFrom( // Compatibilidad Flutter 3+: uso de backgroundColor y foregroundColor backgroundColor: AppColors.surfaceHighest, foregroundColor: AppColors.onSurface, padding: const EdgeInsets.symmetric(vertical: 10), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(8)), elevation: 0, ), child: Text( _serverBloqueado ? 'DESBLOQUEO REMOTO' : 'BLOQUEAR', style: appLabel( size: 11, weight: FontWeight.bold, color: AppColors.onSurface)), ), ), ], ), ), ), ]), ), ); Widget _badgeEstado(bool bloqueado) => Container( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), decoration: BoxDecoration( color: bloqueado ? AppColors.primaryContainer : AppColors.tertiaryContainer, borderRadius: BorderRadius.circular(99)), child: Row(mainAxisSize: MainAxisSize.min, children: [ Icon(bloqueado ? Icons.lock : Icons.lock_open, size: 14, color: bloqueado ? AppColors.primary : AppColors.tertiary), const SizedBox(width: 6), Text(bloqueado ? 'BLOQUEADO' : 'DESBLOQUEADO', style: appLabel( size: 10, weight: FontWeight.bold, color: bloqueado ? AppColors.primary : AppColors.tertiary)), ]), ); // ── Usuarios registrados ──────────────────────────────────────────────────── Widget _usuariosRegistrados() => Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text('Usuarios con Acceso', style: appHeadline(size: 20, weight: FontWeight.bold)), Text('${_usuarios.length} activo${_usuarios.length == 1 ? '' : 's'}', style: appLabel(size: 12, color: AppColors.onSurfaceVariant)), ], ), const SizedBox(height: 16), if (_cargando) const Center( child: Padding( padding: EdgeInsets.symmetric(vertical: 16), child: CircularProgressIndicator( strokeWidth: 2, color: AppColors.primary), )) else if (_usuarios.isEmpty) Container( width: double.infinity, padding: const EdgeInsets.all(20), decoration: BoxDecoration( color: AppColors.surfaceLow, borderRadius: BorderRadius.circular(12)), child: Column(children: [ const Icon(Icons.group_outlined, color: AppColors.outlineVariant, size: 32), const SizedBox(height: 8), Text('Sin usuarios registrados', style: appLabel( size: 13, color: AppColors.outlineVariant)), Text('Usa el botón + para agregar', style: appLabel(size: 11, color: AppColors.outlineVariant)), ]), ) else ..._usuarios.map((u) => Padding( padding: const EdgeInsets.only(bottom: 10), child: _cardUsuario(u), )), ], ); static const _nivelLabels = ['', 'Visitante', 'Empleado', 'Supervisor', 'Admin', 'Super Admin']; static const _nivelColors = [ Colors.transparent, AppColors.outline, AppColors.secondary, AppColors.primary, AppColors.tertiary, AppColors.error, ]; Widget _cardUsuario(Usuario u) { final nivel = u.nivelAcceso.clamp(1, 5); final nColor = _nivelColors[nivel]; final nLabel = _nivelLabels[nivel]; final fechaFin = u.fechaFin != null ? _formatFecha(u.fechaFin!) : null; final vencido = u.fechaFin != null && DateTime.tryParse(u.fechaFin!)?.isBefore(DateTime.now()) == true; return Container( padding: const EdgeInsets.all(14), decoration: BoxDecoration( color: AppColors.surfaceLow, borderRadius: BorderRadius.circular(10), border: Border.all( color: vencido ? AppColors.error.withOpacity(0.3) : AppColors.surfaceHighest, ), ), child: Row(children: [ // Avatar Container( width: 44, height: 44, decoration: BoxDecoration( color: nColor.withOpacity(0.15), borderRadius: BorderRadius.circular(10), border: Border.all(color: nColor.withOpacity(0.3)), ), child: Center( child: Text(u.iniciales, style: appHeadline( size: 15, weight: FontWeight.bold, color: nColor)), ), ), const SizedBox(width: 12), // Info Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row(children: [ Expanded( child: Text(u.nombre, style: appHeadline(size: 14, weight: FontWeight.w600)), ), // Badge nivel Container( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), decoration: BoxDecoration( color: nColor.withOpacity(0.12), borderRadius: BorderRadius.circular(6), ), child: Text('N$nivel · $nLabel', style: appLabel( size: 10, weight: FontWeight.bold, color: nColor)), ), ]), const SizedBox(height: 4), Row(children: [ Icon(Icons.calendar_today, size: 11, color: AppColors.onSurfaceVariant), const SizedBox(width: 4), Text( fechaFin != null ? 'Hasta $fechaFin${vencido ? ' · VENCIDO' : ''}' : 'Sin vencimiento', style: appLabel( size: 11, color: vencido ? AppColors.error : AppColors.onSurfaceVariant), ), if (u.areas != null && u.areas!.isNotEmpty) ...[ const SizedBox(width: 10), Icon(Icons.place_outlined, size: 11, color: AppColors.onSurfaceVariant), const SizedBox(width: 3), Expanded( child: Text( u.areas!.replaceAll(',', ', '), style: appLabel( size: 11, color: AppColors.onSurfaceVariant), overflow: TextOverflow.ellipsis, ), ), ], ]), ]), ), // Botón desactivar IconButton( icon: const Icon(Icons.person_off_outlined, color: AppColors.outline, size: 18), tooltip: 'Desactivar acceso', onPressed: () => _confirmarDesactivar(u), padding: const EdgeInsets.all(8), constraints: const BoxConstraints(), ), ]), ); } String _formatFecha(String iso) { try { final dt = DateTime.parse(iso).toLocal(); return '${dt.day.toString().padLeft(2, '0')}/${dt.month.toString().padLeft(2, '0')}/${dt.year}'; } catch (_) { return '—'; } } Future _confirmarDesactivar(Usuario u) async { final ok = await showDialog( context: context, builder: (_) => AlertDialog( backgroundColor: AppColors.surfaceHigh, title: Text('Desactivar acceso', style: appHeadline( size: 15, weight: FontWeight.w700, color: AppColors.error)), content: Text( 'Se revocará el acceso de "${u.nombre}". Esta acción puede revertirse desde el servidor.', style: appLabel(size: 13, color: AppColors.onSurface), ), actions: [ TextButton( onPressed: () => Navigator.pop(context, false), child: Text('Cancelar', style: appLabel(color: AppColors.onSurfaceVariant)), ), TextButton( onPressed: () => Navigator.pop(context, true), child: Text('DESACTIVAR', style: appLabel( weight: FontWeight.bold, color: AppColors.error)), ), ], ), ); if (ok != true) return; await _usuariosDao.desactivar(u.id); _cargar(); } // ── Registro de acceso ────────────────────────────────────────────────────── Widget _registroAcceso() => Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text('Registro de Acceso', style: appHeadline(size: 20, weight: FontWeight.bold)), const SizedBox(height: 16), if (_cargando) const Center(child: Padding( padding: EdgeInsets.symmetric(vertical: 24), child: CircularProgressIndicator( strokeWidth: 2, color: AppColors.primary), )) else if (_accesos.isEmpty) Container( width: double.infinity, padding: const EdgeInsets.all(24), decoration: BoxDecoration(color: AppColors.surfaceLow, borderRadius: BorderRadius.circular(12)), child: Column(children: [ const Icon(Icons.no_accounts_outlined, color: AppColors.outlineVariant, size: 32), const SizedBox(height: 8), Text('Sin registros de acceso', style: appLabel(size: 13, color: AppColors.outlineVariant)), Text('Carga datos de demo o sincroniza', style: appLabel(size: 11, color: AppColors.outlineVariant)), ]), ) else ..._accesos.asMap().entries.map((e) { final a = e.value; final autorizado = (a['autorizado'] as int) == 1; final nombre = a['usuario_nombre'] as String? ?? 'Usuario'; final iniciales = a['usuario_iniciales'] as String? ?? _iniciales(nombre); final puerta = a['puerta_nombre'] as String? ?? '—'; final metodo = _metodoLabel(a['metodo'] as String? ?? 'pin'); final hora = _horaCorta(a['timestamp'] as String? ?? ''); final desc = '$puerta · ${autorizado ? metodo : 'Acceso Denegado'}'; return Padding( padding: const EdgeInsets.only(bottom: 20), child: _entradaLog( iniciales: iniciales, colorAvatar: autorizado ? AppColors.primary : AppColors.error, nombre: nombre, hora: hora, descripcion: desc, descColor: autorizado ? AppColors.onSurfaceVariant : AppColors.error, estadoOk: autorizado, ), ); }).toList(), ], ); String _iniciales(String nombre) { final partes = nombre.trim().split(' '); if (partes.length >= 2) { return '${partes.first[0]}${partes.last[0]}'.toUpperCase(); } return nombre.isNotEmpty ? nombre[0].toUpperCase() : '?'; } Widget _entradaLog({ required String iniciales, required Color colorAvatar, required String nombre, required String hora, required String descripcion, required Color descColor, required bool estadoOk, }) => Row(crossAxisAlignment: CrossAxisAlignment.start, children: [ Stack(clipBehavior: Clip.none, children: [ Container( width: 48, height: 48, decoration: BoxDecoration( color: colorAvatar.withOpacity(0.15), borderRadius: BorderRadius.circular(12), border: Border.all(color: colorAvatar.withOpacity(0.3)), ), child: Center( child: Text(iniciales, style: appHeadline( size: 16, weight: FontWeight.bold, color: colorAvatar)), ), ), Positioned( bottom: -4, right: -4, child: Container( width: 20, height: 20, decoration: BoxDecoration( color: estadoOk ? AppColors.primary : AppColors.tertiary, borderRadius: BorderRadius.circular(6), border: Border.all(color: AppColors.surfaceLowest, width: 2), ), child: Icon( estadoOk ? Icons.check : Icons.warning, size: 11, color: estadoOk ? AppColors.primaryContainer : AppColors.tertiaryContainer, ), ), ), ]), const SizedBox(width: 16), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text(nombre, style: appHeadline(size: 14)), Text(hora, style: appLabel(size: 10)), ]), const SizedBox(height: 4), Text(descripcion, style: appLabel(size: 13, color: descColor)), ], )), ]); // ── Snapshot de cámara ────────────────────────────────────────────────────── Widget _snapshotCamara() => Container( padding: const EdgeInsets.all(16), decoration: BoxDecoration( color: AppColors.surfaceLow, borderRadius: BorderRadius.circular(12)), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row(children: [ const Icon(Icons.photo_camera, color: AppColors.primary, size: 18), const SizedBox(width: 8), Text('FOTO ENTRADA 01', style: appLabel( size: 10, weight: FontWeight.bold, spacing: 2.0)), ]), const SizedBox(height: 12), ClipRRect( borderRadius: BorderRadius.circular(8), child: SizedBox( height: 160, width: double.infinity, child: Stack(children: [ Container( decoration: const BoxDecoration( gradient: RadialGradient( center: Alignment(0.3, -0.2), radius: 1.5, colors: [Color(0xFF0D1F2D), Color(0xFF050A0E)], ), ), ), CustomPaint( size: const Size(double.infinity, 160), painter: _GridPainterGreen()), // Figuras decorativas CCTV Positioned( left: 40, top: 20, child: _cctvBox( 80, 60, AppColors.primary.withOpacity(0.15))), Positioned( right: 60, top: 40, child: _cctvBox( 50, 40, AppColors.primary.withOpacity(0.08))), // Overlay oscuro inferior Container( decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.bottomCenter, end: Alignment.topCenter, colors: [ Colors.black.withOpacity(0.6), Colors.transparent ], ), ), ), Positioned( top: 8, left: 8, child: Container( padding: const EdgeInsets.symmetric( horizontal: 8, vertical: 3), decoration: BoxDecoration( color: AppColors.error.withOpacity(0.85), borderRadius: BorderRadius.circular(4)), child: Text('● GRABANDO EN VIVO', style: appLabel( size: 9, weight: FontWeight.bold, color: Colors.white, spacing: 0.5)), ), ), Positioned( bottom: 8, right: 8, child: Text('CAM_01_LOBBY_H264', style: appLabel(size: 9, color: Colors.white54)), ), ]), ), ), ], ), ); Widget _cctvBox(double w, double h, Color color) => Container( width: w, height: h, decoration: BoxDecoration( border: Border.all(color: color, width: 1), color: color.withOpacity(0.05), ), ); } class _GridPainterGreen extends CustomPainter { @override void paint(Canvas canvas, Size size) { final p = Paint() ..color = const Color(0xFF0B3D2E).withOpacity(0.6) ..strokeWidth = 0.5; for (double x = 0; x <= size.width; x += 18) { canvas.drawLine(Offset(x, 0), Offset(x, size.height), p); } for (double y = 0; y <= size.height; y += 18) { canvas.drawLine(Offset(0, y), Offset(size.width, y), p); } } @override bool shouldRepaint(covariant CustomPainter o) => false; }