Files

676 lines
26 KiB
Dart

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:file_picker/file_picker.dart';
import '../theme.dart';
import '../models/usuario.dart';
import '../db/dao/usuarios_dao.dart';
import '../services/whatsapp_alert_service.dart';
import '../main.dart' show LoginPage;
import 'settings_page.dart';
import 'seguridad_page.dart';
import 'mensageria_page.dart';
import 'historial_sesiones_page.dart';
class PerfilUsuarioPage extends StatefulWidget {
const PerfilUsuarioPage({Key? key}) : super(key: key);
@override
State<PerfilUsuarioPage> createState() => _PerfilUsuarioPageState();
}
class _PerfilUsuarioPageState extends State<PerfilUsuarioPage> {
final _dao = UsuariosDao();
Usuario? _usuario;
bool _cargando = true;
@override
void initState() {
super.initState();
_cargar();
}
Future<void> _cargar() async {
try {
final u = await _dao.getById(1);
if (mounted) setState(() { _usuario = u; _cargando = false; });
} catch (_) {
if (mounted) setState(() => _cargando = false);
}
}
// ── Calcular iniciales desde el nombre ────────────────────────────────────
String _calcularIniciales(String nombre) {
final partes = nombre.trim().split(RegExp(r'\s+'));
if (partes.length == 1) return partes[0][0].toUpperCase();
return (partes.first[0] + partes.last[0]).toUpperCase();
}
// ── Editar nombre ─────────────────────────────────────────────────────────
Future<void> _editarNombre() async {
if (_usuario == null) return;
final ctrl = TextEditingController(text: _usuario!.nombre);
final nuevoNombre = await showDialog<String>(
context: context,
builder: (_) => AlertDialog(
backgroundColor: AppColors.surfaceHigh,
title: Text('Editar nombre',
style: appHeadline(size: 16, weight: FontWeight.w700)),
content: TextField(
controller: ctrl,
autofocus: true,
style: appHeadline(size: 14),
decoration: InputDecoration(
hintText: 'Nombre completo',
hintStyle: appLabel(size: 13, color: AppColors.outline),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: const BorderSide(color: AppColors.outlineVariant),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: const BorderSide(color: AppColors.primary, width: 2),
),
filled: true,
fillColor: AppColors.surfaceHighest,
contentPadding: const EdgeInsets.symmetric(
horizontal: 14, vertical: 12),
),
textCapitalization: TextCapitalization.words,
onSubmitted: (v) => Navigator.pop(context, v.trim()),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: Text('Cancelar',
style: appLabel(size: 13,
color: AppColors.onSurfaceVariant)),
),
TextButton(
onPressed: () => Navigator.pop(context, ctrl.text.trim()),
child: Text('Guardar',
style: appLabel(size: 13,
weight: FontWeight.bold, color: AppColors.primary)),
),
],
),
);
ctrl.dispose();
if (nuevoNombre == null || nuevoNombre.isEmpty) return;
final actualizado = _usuario!.copyWith(
nombre: nuevoNombre,
iniciales: _calcularIniciales(nuevoNombre),
sincronizado: false,
);
await _dao.update(actualizado);
if (mounted) setState(() => _usuario = actualizado);
}
// ── Seleccionar foto de perfil ────────────────────────────────────────────
Future<void> _seleccionarFoto() async {
final result = await FilePicker.platform.pickFiles(
type: FileType.image,
allowMultiple: false,
);
if (result == null || result.files.isEmpty) return;
final path = result.files.first.path;
if (path == null || _usuario == null) return;
await _dao.updateFoto(_usuario!.id, path);
if (mounted) setState(() => _usuario = _usuario!.copyWith(fotoPath: path));
}
// ── Editar teléfono para WhatsApp de alertas críticas ─────────────────────
// Se valida mediante expresión regular el código de país internacional E.164
Future<void> _editarTelefono() async {
if (_usuario == null) return;
final ctrl = TextEditingController(text: _usuario!.telefono ?? '');
String? errorTexto;
// Función de validación con regex para formato internacional con código de país
String? validarNumero(String valor) {
final normalizado = WhatsAppAlertService.normalizarTelefono(valor);
if (normalizado.isEmpty) {
return null; // Permitir campo vacío para borrar el número
}
if (normalizado.startsWith('0')) {
return 'No debe iniciar con 0. Incluye código de país (ej. +593...)';
}
if (!WhatsAppAlertService.esNumeroValido(normalizado)) {
return 'Código de país obligatorio (ej. +5939XXXXXXXX)';
}
return null;
}
final nuevoTelefono = await showDialog<String?>(
context: context,
builder: (ctx) {
return StatefulBuilder(
builder: (context, setDialogState) {
return AlertDialog(
backgroundColor: AppColors.surfaceHigh,
title: Row(
children: [
const Icon(Icons.phone_android,
color: AppColors.secondary, size: 22),
const SizedBox(width: 8),
Text('WhatsApp de Alertas',
style: appHeadline(size: 16, weight: FontWeight.w700)),
],
),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Ingresa tu número con código de país para recibir alertas de intrusión, coacción y botón de pánico vía sigma-robot.',
style:
appLabel(size: 12, color: AppColors.onSurfaceVariant),
),
const SizedBox(height: 16),
TextField(
controller: ctrl,
autofocus: true,
keyboardType: TextInputType.phone,
style: appHeadline(size: 15),
onChanged: (v) {
setDialogState(() {
errorTexto = validarNumero(v);
});
},
decoration: InputDecoration(
prefixIcon: const Icon(Icons.phone_android,
color: AppColors.secondary, size: 20),
hintText: '+5939XXXXXXXX',
hintStyle: appLabel(size: 13, color: AppColors.outline),
errorText: errorTexto,
errorMaxLines: 2,
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide:
const BorderSide(color: AppColors.outlineVariant),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: const BorderSide(
color: AppColors.secondary, width: 2),
),
filled: true,
fillColor: AppColors.surfaceHighest,
contentPadding: const EdgeInsets.symmetric(
horizontal: 14, vertical: 12),
),
),
const SizedBox(height: 10),
Text(
'Formato internacional: +[código_país][número]\nEjemplo Ecuador: +593987654321',
style: appLabel(size: 11, color: AppColors.outline),
),
],
),
actions: [
if (_usuario!.telefono != null &&
_usuario!.telefono!.isNotEmpty)
TextButton(
onPressed: () => Navigator.pop(ctx, ''),
child: Text('Eliminar',
style: appLabel(size: 13, color: AppColors.error)),
),
TextButton(
onPressed: () => Navigator.pop(ctx, null),
child: Text('Cancelar',
style: appLabel(
size: 13, color: AppColors.onSurfaceVariant)),
),
TextButton(
onPressed: () {
final err = validarNumero(ctrl.text);
if (err != null) {
setDialogState(() => errorTexto = err);
return;
}
final valorFinal = ctrl.text.trim().isEmpty
? null
: WhatsAppAlertService.normalizarTelefono(ctrl.text);
Navigator.pop(ctx, valorFinal ?? '');
},
child: Text('Guardar',
style: appLabel(
size: 13,
weight: FontWeight.bold,
color: AppColors.secondary)),
),
],
);
},
);
},
);
ctrl.dispose();
if (nuevoTelefono == null) return; // Operación cancelada
final valorPersistir = nuevoTelefono.isEmpty ? null : nuevoTelefono;
final actualizado = _usuario!.copyWith(
telefono: valorPersistir,
sincronizado: false,
);
// Persiste el nuevo número en la tabla usuarios de SQLite
await _dao.update(actualizado);
if (mounted) {
setState(() => _usuario = actualizado);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
valorPersistir != null
? 'Número de WhatsApp registrado: $valorPersistir'
: 'Número de WhatsApp eliminado',
style: appLabel(size: 13, color: AppColors.onSurface),
),
backgroundColor: AppColors.surfaceHigh,
duration: const Duration(seconds: 3),
),
);
}
}
@override
Widget build(BuildContext context) {
if (_cargando) {
return const Center(
child: CircularProgressIndicator(color: AppColors.primary));
}
final nombre = _usuario?.nombre ?? 'Sin nombre';
final iniciales = _usuario?.iniciales ?? '?';
final nivel = _usuario?.nivelAcceso ?? 1;
final nivelLabel = nivel >= 3 ? 'ACCESO TOTAL' : 'ACCESO NIVEL $nivel';
return SingleChildScrollView(
primary: false,
padding: const EdgeInsets.fromLTRB(24, 24, 24, 24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_avatarCard(nombre, iniciales, nivel, nivelLabel),
const SizedBox(height: 16),
_whatsappCard(),
const SizedBox(height: 24),
_statsGrid(),
const SizedBox(height: 32),
_seccionOpciones(context),
const SizedBox(height: 32),
_botonCerrarSesion(context),
],
),
);
}
// ── Tarjeta de Teléfono / WhatsApp para alertas críticas ──────────────────
Widget _whatsappCard() {
final telefono = _usuario?.telefono;
final tieneTelefono = telefono != null && telefono.trim().isNotEmpty;
return Container(
width: double.infinity,
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: AppColors.surfaceHigh,
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: tieneTelefono
? AppColors.secondary.withOpacity(0.35)
: AppColors.outlineVariant,
width: 1,
),
),
child: Row(
children: [
Container(
width: 44,
height: 44,
decoration: BoxDecoration(
color: tieneTelefono
? AppColors.secondary.withOpacity(0.15)
: AppColors.surfaceHighest,
borderRadius: BorderRadius.circular(10),
),
child: Icon(
Icons.phone_android,
color: tieneTelefono ? AppColors.secondary : AppColors.outline,
size: 24,
),
),
const SizedBox(width: 14),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Text(
'WHATSAPP DE ALERTAS',
style: appLabel(
size: 10,
weight: FontWeight.bold,
color: tieneTelefono
? AppColors.secondary
: AppColors.onSurfaceVariant,
spacing: 1.5,
),
),
const SizedBox(width: 8),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: tieneTelefono
? AppColors.secondaryContainer
: AppColors.surfaceLowest,
borderRadius: BorderRadius.circular(4),
),
child: Text(
tieneTelefono ? 'ACTIVO' : 'SIN CONFIGURAR',
style: appLabel(
size: 9,
weight: FontWeight.bold,
color: tieneTelefono
? AppColors.secondary
: AppColors.outline,
),
),
),
],
),
const SizedBox(height: 4),
Text(
tieneTelefono ? telefono : 'Sin número configurado',
style: appHeadline(
size: 14,
weight: FontWeight.w600,
color: tieneTelefono
? AppColors.onSurface
: AppColors.outline,
),
),
const SizedBox(height: 2),
Text(
'Recepción de alertas de pánico y severidad 4-5',
style: appLabel(size: 11, color: AppColors.onSurfaceVariant),
),
],
),
),
IconButton(
icon: Icon(
tieneTelefono ? Icons.edit_outlined : Icons.add_circle_outline,
color: tieneTelefono ? AppColors.secondary : AppColors.primary,
size: 22,
),
onPressed: _editarTelefono,
tooltip: 'Configurar WhatsApp de alertas',
),
],
),
);
}
// ── Avatar + info ──────────────────────────────────────────────────────────
Widget _avatarCard(String nombre, String iniciales, int nivel,
String nivelLabel) =>
Container(
width: double.infinity,
padding: const EdgeInsets.all(24),
decoration: BoxDecoration(
color: AppColors.surfaceHigh,
borderRadius: BorderRadius.circular(12)),
child: Column(children: [
Stack(clipBehavior: Clip.none, children: [
// ── Círculo avatar ───────────────────────────────────────────
GestureDetector(
onTap: _seleccionarFoto,
child: Container(
width: 80, height: 80,
decoration: BoxDecoration(
shape: BoxShape.circle,
gradient: _usuario?.fotoPath == null
? const LinearGradient(
colors: [AppColors.primary, AppColors.primaryContainer],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
)
: null,
boxShadow: [BoxShadow(
color: AppColors.primary.withOpacity(0.3),
blurRadius: 20, spreadRadius: 2,
)],
),
child: ClipOval(
child: _usuario?.fotoPath != null
? Image.file(
File(_usuario!.fotoPath!),
width: 80, height: 80,
fit: BoxFit.cover,
errorBuilder: (_, __, ___) => _avatarIniciales(iniciales),
)
: _avatarIniciales(iniciales),
),
),
),
// ── Botón cámara ─────────────────────────────────────────────
Positioned(
bottom: 0, right: 0,
child: GestureDetector(
onTap: _seleccionarFoto,
child: Container(
width: 26, height: 26,
decoration: BoxDecoration(
color: AppColors.primary,
shape: BoxShape.circle,
border: Border.all(
color: AppColors.surfaceHigh, width: 2),
),
child: const Icon(Icons.camera_alt,
size: 13, color: AppColors.primaryContainer),
),
),
),
]),
const SizedBox(height: 16),
// ── Nombre con botón editar ──────────────────────────────────
Row(mainAxisAlignment: MainAxisAlignment.center, children: [
Text(nombre,
style: appHeadline(size: 20, weight: FontWeight.w800)),
const SizedBox(width: 8),
GestureDetector(
onTap: _editarNombre,
child: const Icon(Icons.edit,
size: 15, color: AppColors.primary),
),
]),
const SizedBox(height: 4),
Text('Operador de Seguridad', style: appLabel(size: 13)),
const SizedBox(height: 12),
Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
decoration: BoxDecoration(
color: AppColors.primaryContainer,
borderRadius: BorderRadius.circular(99)),
child: Text('NIVEL $nivel · $nivelLabel',
style: appLabel(size: 10, weight: FontWeight.bold,
color: AppColors.primary, spacing: 1.5)),
),
]),
);
Widget _avatarIniciales(String iniciales) => Center(
child: Text(iniciales,
style: appHeadline(
size: 28,
weight: FontWeight.w800,
color: AppColors.primaryContainer)),
);
// ── Estadísticas ───────────────────────────────────────────────────────────
Widget _statsGrid() => Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('ESTADÍSTICAS DEL TURNO',
style: appLabel(size: 10, weight: FontWeight.bold,
color: AppColors.onSurfaceVariant, spacing: 2.0)),
const SizedBox(height: 12),
Row(children: [
Expanded(child: _statItem('142', 'Alarmas\ngestionadas',
Icons.notifications_active, AppColors.primary)),
const SizedBox(width: 12),
Expanded(child: _statItem('38', 'Accesos\nautorizados',
Icons.lock_open, AppColors.secondary)),
const SizedBox(width: 12),
Expanded(child: _statItem('03', 'Alertas\nactivas',
Icons.warning, AppColors.error)),
]),
],
);
Widget _statItem(String valor, String label, IconData icon, Color color) =>
Container(
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
color: AppColors.surfaceLow,
borderRadius: BorderRadius.circular(12)),
child: Column(children: [
Icon(icon, color: color, size: 20),
const SizedBox(height: 8),
Text(valor, style: appHeadline(size: 22, color: color)),
const SizedBox(height: 4),
Text(label, style: appLabel(size: 10), textAlign: TextAlign.center),
]),
);
// ── Opciones ───────────────────────────────────────────────────────────────
Widget _seccionOpciones(BuildContext context) => Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('CUENTA',
style: appLabel(size: 10, weight: FontWeight.bold,
color: AppColors.onSurfaceVariant, spacing: 2.0)),
const SizedBox(height: 12),
_opcionItem(Icons.settings, 'Configuración',
'Notificaciones, sonido y alarmas', () {
Navigator.push(context,
MaterialPageRoute(builder: (_) => const SettingsPage()));
}),
const Divider(color: AppColors.outlineVariant, height: 1),
_opcionItem(Icons.shield_outlined, 'Seguridad',
'Cambiar PIN de acceso', () {
Navigator.push(context,
MaterialPageRoute(builder: (_) => const SeguridadPage()));
}),
const Divider(color: AppColors.outlineVariant, height: 1),
_opcionItem(Icons.history, 'Historial de sesiones',
'Últimos accesos al sistema', () {
Navigator.push(context,
MaterialPageRoute(
builder: (_) => const HistorialSesionesPage()));
}),
const Divider(color: AppColors.outlineVariant, height: 1),
_opcionItem(Icons.help_outline, 'Ayuda y soporte',
'Contactar con soporte técnico', () {
Navigator.push(context,
MaterialPageRoute(builder: (_) => const MensajeriaPage()));
}),
],
);
Widget _opcionItem(IconData icon, String titulo, String subtitulo,
VoidCallback onTap) =>
InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(8),
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 14),
child: Row(children: [
Container(
width: 40, height: 40,
decoration: BoxDecoration(
color: AppColors.surfaceHighest,
borderRadius: BorderRadius.circular(10)),
child: Icon(icon, color: AppColors.primary, size: 20),
),
const SizedBox(width: 16),
Expanded(child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(titulo, style: appHeadline(size: 14)),
const SizedBox(height: 2),
Text(subtitulo, style: appLabel(size: 12)),
],
)),
const Icon(Icons.chevron_right,
color: AppColors.outlineVariant, size: 20),
]),
),
);
// ── Cerrar sesión ──────────────────────────────────────────────────────────
Widget _botonCerrarSesion(BuildContext context) => SizedBox(
width: double.infinity,
child: OutlinedButton.icon(
onPressed: () => _cerrarSesion(context),
icon: const Icon(Icons.logout, color: AppColors.error, size: 18),
label: Text('Cerrar Sesión',
style: appLabel(size: 14, weight: FontWeight.bold,
color: AppColors.error)),
style: OutlinedButton.styleFrom(
side: const BorderSide(color: AppColors.error, width: 1),
padding: const EdgeInsets.symmetric(vertical: 14),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12)),
),
),
);
Future<void> _cerrarSesion(BuildContext context) async {
final confirmar = await showDialog<bool>(
context: context,
builder: (_) => AlertDialog(
backgroundColor: AppColors.surfaceHigh,
title: Text('Cerrar sesión',
style: appHeadline(size: 16, weight: FontWeight.w700)),
content: Text('¿Seguro que deseas cerrar sesión?',
style: appLabel(size: 13)),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: Text('Cancelar',
style: appLabel(size: 13,
color: AppColors.onSurfaceVariant)),
),
TextButton(
onPressed: () => Navigator.pop(context, true),
child: Text('Cerrar sesión',
style: appLabel(size: 13, weight: FontWeight.bold,
color: AppColors.error)),
),
],
),
);
if (confirmar != true) return;
final prefs = await SharedPreferences.getInstance();
await prefs.remove('autologin');
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(builder: (_) => const LoginPage()),
(_) => false,
);
}
}