import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'package:provider/provider.dart'; import '../../providers/app_provider.dart'; import '../../theme/app_theme.dart'; import '../../models/pedido.dart'; import '../../models/moneda.dart'; // Utilidades de validación regex para teléfonos y servicio de alertas vía Sigma-Robot import '../../utils/phone_utils.dart'; import '../../services/whatsapp_service.dart'; class PerfilScreen extends StatelessWidget { const PerfilScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final provider = context.watch(); final vendedor = provider.vendedor; final fmt = provider.currencyFormat; return Scaffold( backgroundColor: AppTheme.bgColor, body: CustomScrollView( slivers: [ _buildSliverHeader(context, vendedor, provider), SliverPadding( padding: const EdgeInsets.all(16), sliver: SliverList( delegate: SliverChildListDelegate([ _buildStatsRow(provider, fmt), const SizedBox(height: 20), _buildRutaProgress(provider), const SizedBox(height: 20), _buildPedidosResumen(context, provider, fmt), const SizedBox(height: 20), // Tarjeta de información con soporte de edición de teléfono para WhatsApp _buildInfoCard(context, vendedor, provider), const SizedBox(height: 20), _buildConfigSection(context, provider), const SizedBox(height: 20), _buildLogoutBtn(context, provider), const SizedBox(height: 40), ]), ), ), ], ), ); } Widget _buildSliverHeader(BuildContext context, vendedor, AppProvider provider) { return SliverAppBar( expandedHeight: 200, pinned: true, backgroundColor: AppTheme.primaryColor, flexibleSpace: FlexibleSpaceBar( background: Container( decoration: const BoxDecoration( gradient: LinearGradient( colors: [Color(0xFF1E3A8A), Color(0xFF2563EB)], begin: Alignment.topCenter, end: Alignment.bottomCenter, ), ), child: SafeArea( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ CircleAvatar( radius: 40, backgroundColor: Colors.white.withOpacity(0.2), child: Text( vendedor.avatarInitials, style: const TextStyle(fontSize: 28, fontWeight: FontWeight.bold, color: Colors.white), ), ), const SizedBox(height: 10), Text(vendedor.nombre, style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: Colors.white)), const SizedBox(height: 4), Container( padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4), decoration: BoxDecoration( color: Colors.white.withOpacity(0.2), borderRadius: BorderRadius.circular(12), ), child: Row( mainAxisSize: MainAxisSize.min, children: [ const Icon(Icons.location_on, color: Colors.white70, size: 14), const SizedBox(width: 4), Text(vendedor.zona, style: const TextStyle(color: Colors.white, fontSize: 12, fontWeight: FontWeight.w500)), ], ), ), const SizedBox(height: 8), Container( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 3), decoration: BoxDecoration( color: provider.modoOnline ? Colors.green.withOpacity(0.3) : Colors.orange.withOpacity(0.3), borderRadius: BorderRadius.circular(10), border: Border.all( color: provider.modoOnline ? Colors.greenAccent.withOpacity(0.6) : Colors.orangeAccent.withOpacity(0.6), ), ), child: Row( mainAxisSize: MainAxisSize.min, children: [ Icon( provider.modoOnline ? Icons.cloud_done_outlined : Icons.cloud_off_outlined, color: Colors.white, size: 13, ), const SizedBox(width: 4), Text( provider.modoOnline ? 'SIGMAC Cloud' : 'Modo offline', style: const TextStyle(color: Colors.white, fontSize: 11, fontWeight: FontWeight.w600), ), ], ), ), ], ), ), ), title: Text(vendedor.nombre, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), titlePadding: const EdgeInsets.only(left: 16, bottom: 12), ), ); } Widget _buildStatsRow(AppProvider provider, NumberFormat fmt) { final stats = [ {'label': 'Pedidos hoy', 'value': '${provider.pedidosHoy}', 'color': AppTheme.primaryColor}, {'label': 'Ventas hoy', 'value': fmt.format(provider.ventasTotalesHoy), 'color': AppTheme.successColor}, { 'label': 'Clientes', 'value': '${provider.ruta.visitadas}/${provider.ruta.paradas.length}', 'color': AppTheme.accentColor }, ]; return Row( children: stats.map((s) { final color = s['color'] as Color; return Expanded( child: Container( margin: const EdgeInsets.symmetric(horizontal: 4), padding: const EdgeInsets.symmetric(vertical: 14), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(12), boxShadow: [BoxShadow(color: color.withOpacity(0.1), blurRadius: 8)], ), child: Column( children: [ Text(s['value'] as String, style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: color)), const SizedBox(height: 4), Text(s['label'] as String, style: const TextStyle(fontSize: 10, color: AppTheme.textSecondary), textAlign: TextAlign.center), ], ), ), ); }).toList(), ); } Widget _buildRutaProgress(AppProvider provider) { final ruta = provider.ruta; final progress = ruta.paradas.isEmpty ? 0.0 : ruta.visitadas / ruta.paradas.length; return _card( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const Text('Progreso de ruta', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14)), Text('${(progress * 100).toInt()}% completado', style: const TextStyle(fontSize: 12, color: AppTheme.textSecondary)), ], ), const SizedBox(height: 12), ClipRRect( borderRadius: BorderRadius.circular(6), child: LinearProgressIndicator( value: progress, backgroundColor: AppTheme.bgColor, valueColor: AlwaysStoppedAnimation( progress == 1.0 ? AppTheme.successColor : AppTheme.primaryColor, ), minHeight: 10, ), ), const SizedBox(height: 10), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ _progressChip(Icons.check_circle, '${ruta.visitadas} visitadas', AppTheme.successColor), _progressChip(Icons.pending, '${ruta.pendientes} pendientes', AppTheme.warningColor), _progressChip(Icons.location_on, '${ruta.paradas.length} total', AppTheme.primaryColor), ], ), ], ), ); } Widget _progressChip(IconData icon, String label, Color color) { return Row( mainAxisSize: MainAxisSize.min, children: [ Icon(icon, size: 14, color: color), const SizedBox(width: 4), Text(label, style: TextStyle(fontSize: 11, color: color, fontWeight: FontWeight.w500)), ], ); } Widget _buildPedidosResumen(BuildContext context, AppProvider provider, NumberFormat fmt) { final estados = { EstadoPedido.confirmado: provider.pedidos.where((p) => p.estado == EstadoPedido.confirmado).length, EstadoPedido.entregado: provider.pedidos.where((p) => p.estado == EstadoPedido.entregado).length, EstadoPedido.pendiente: provider.pedidos.where((p) => p.estado == EstadoPedido.pendiente).length, EstadoPedido.cancelado: provider.pedidos.where((p) => p.estado == EstadoPedido.cancelado).length, }; return _card( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Text('Resumen de pedidos', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14)), const SizedBox(height: 12), ...estados.entries.map((e) { final color = AppTheme.estadoColor(e.key.label); return Padding( padding: const EdgeInsets.only(bottom: 8), child: Row( children: [ Container(width: 10, height: 10, decoration: BoxDecoration(color: color, shape: BoxShape.circle)), const SizedBox(width: 10), Text(e.key.label, style: const TextStyle(fontSize: 13)), const Spacer(), Text('${e.value}', style: TextStyle(fontWeight: FontWeight.bold, color: color)), ], ), ); }).toList(), ], ), ); } Widget _buildInfoCard(BuildContext context, vendedor, AppProvider provider) { final tieneWhatsAppValido = PhoneUtils.esWhatsAppValido(vendedor.telefono); final telefonoFormateado = vendedor.telefono.isNotEmpty ? PhoneUtils.formatearVisual(vendedor.telefono) : 'Sin configurar'; return _card( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const Text('Información de contacto', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14)), TextButton.icon( style: TextButton.styleFrom( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), minimumSize: Size.zero, tapTargetSize: MaterialTapTargetSize.shrinkWrap, ), icon: const Icon(Icons.edit, size: 14, color: AppTheme.primaryColor), label: const Text('Editar WhatsApp', style: TextStyle(fontSize: 11, color: AppTheme.primaryColor)), onPressed: () => _mostrarDialogoWhatsApp(context, provider), ), ], ), const SizedBox(height: 12), _infoTile(Icons.email_outlined, 'Correo', vendedor.email), // Fila interactiva para el teléfono con indicador de estado WhatsApp InkWell( borderRadius: BorderRadius.circular(8), onTap: () => _mostrarDialogoWhatsApp(context, provider), child: Padding( padding: const EdgeInsets.symmetric(vertical: 4), child: Row( children: [ Icon(Icons.phone_outlined, size: 18, color: AppTheme.primaryColor), const SizedBox(width: 10), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Text('Teléfono / WhatsApp', style: TextStyle(fontSize: 10, color: AppTheme.textSecondary)), Text(telefonoFormateado, style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w500)), ], ), ), Container( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), decoration: BoxDecoration( color: tieneWhatsAppValido ? Colors.green.withOpacity(0.12) : Colors.amber.withOpacity(0.15), borderRadius: BorderRadius.circular(10), ), child: Row( mainAxisSize: MainAxisSize.min, children: [ Icon( tieneWhatsAppValido ? Icons.verified : Icons.warning_amber_rounded, size: 12, color: tieneWhatsAppValido ? Colors.green.shade700 : Colors.amber.shade800, ), const SizedBox(width: 4), Text( tieneWhatsAppValido ? 'Vinculado' : 'Sin validar', style: TextStyle( fontSize: 10, fontWeight: FontWeight.w600, color: tieneWhatsAppValido ? Colors.green.shade800 : Colors.amber.shade900, ), ), ], ), ), ], ), ), ), const SizedBox(height: 6), _infoTile(Icons.map_outlined, 'Zona', vendedor.zona), ], ), ); } Widget _infoTile(IconData icon, String label, String value) { return Padding( padding: const EdgeInsets.only(bottom: 10), child: Row( children: [ Icon(icon, size: 18, color: AppTheme.primaryColor), const SizedBox(width: 10), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(label, style: const TextStyle(fontSize: 10, color: AppTheme.textSecondary)), Text(value, style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w500)), ], ), ], ), ); } Widget _buildConfigSection(BuildContext context, AppProvider provider) { final vendedor = provider.vendedor; final tieneWhatsApp = PhoneUtils.esWhatsAppValido(vendedor.telefono); final opciones = [ {'icon': Icons.notifications_outlined, 'label': 'Notificaciones', 'trailing': true}, // Opción dedicada para configurar y probar alertas WhatsApp mediante Sigma-Robot { 'icon': Icons.mark_chat_read_outlined, 'label': 'Alertas WhatsApp (Sigma-Robot)', 'value': tieneWhatsApp ? PhoneUtils.formatearVisual(vendedor.telefono) : 'Configurar', 'onTap': () => _mostrarDialogoWhatsApp(context, provider), }, { 'icon': Icons.attach_money, 'label': 'Moneda', 'value': '${provider.moneda.codigo} (${provider.moneda.simbolo})', 'onTap': () => _mostrarSelectorMoneda(context, provider), }, {'icon': Icons.language, 'label': 'Idioma', 'value': 'Español'}, {'icon': Icons.help_outline, 'label': 'Ayuda y soporte', 'arrow': true}, {'icon': Icons.info_outline, 'label': 'Acerca de la app', 'value': 'v1.0.1'}, ]; return _card( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Text('Configuración', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14)), const SizedBox(height: 8), ...opciones.map((o) => ListTile( dense: true, contentPadding: EdgeInsets.zero, leading: Icon(o['icon'] as IconData, color: AppTheme.primaryColor, size: 22), title: Text(o['label'] as String, style: const TextStyle(fontSize: 13)), trailing: o['trailing'] == true ? Switch(value: true, onChanged: (_) {}, activeColor: AppTheme.primaryColor) : o['arrow'] == true ? const Icon(Icons.chevron_right, color: AppTheme.textSecondary) : Row( mainAxisSize: MainAxisSize.min, children: [ Text(o['value'] as String? ?? '', style: const TextStyle(fontSize: 12, color: AppTheme.textSecondary)), if (o['onTap'] != null) ...[ const SizedBox(width: 4), const Icon(Icons.chevron_right, size: 16, color: AppTheme.textSecondary), ], ], ), onTap: (o['onTap'] as VoidCallback?) ?? () {}, )).toList(), ], ), ); } // ── Modal de Configuración y Alertas de WhatsApp ─────────────── // Permite al usuario registrar o actualizar su número móvil con selección de código // de país, previsualización regex en tiempo real y envío de mensaje de prueba vía Sigma-Robot void _mostrarDialogoWhatsApp(BuildContext context, AppProvider provider) { final vendedor = provider.vendedor; String codigoPais = PhoneUtils.defaultCountryCode; // Detectar si el teléfono actual ya tiene un código de país conocido String textoInicial = vendedor.telefono; for (final p in PhoneUtils.paisesDisponibles) { final digitos = PhoneUtils.extraerSoloDigitos(textoInicial); if (digitos.startsWith(p.codigo)) { codigoPais = p.codigo; textoInicial = digitos.substring(p.codigo.length); break; } } final phoneCtrl = TextEditingController(text: textoInicial); bool enviandoPrueba = false; showModalBottomSheet( context: context, isScrollControlled: true, shape: const RoundedRectangleBorder( borderRadius: BorderRadius.vertical(top: Radius.circular(20)), ), builder: (ctx) { return StatefulBuilder( builder: (ctx, setModalState) { final textoIngresado = phoneCtrl.text.trim(); final normalizado = PhoneUtils.normalizarWhatsApp(textoIngresado, pais: codigoPais); final esValido = PhoneUtils.esWhatsAppValido(normalizado); final paisActual = PhoneUtils.paisesDisponibles.firstWhere( (p) => p.codigo == codigoPais, orElse: () => PhoneUtils.paisesDisponibles.first, ); return Padding( padding: EdgeInsets.only( left: 20, right: 20, top: 20, bottom: MediaQuery.of(ctx).viewInsets.bottom + 20, ), child: SingleChildScrollView( child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Container( padding: const EdgeInsets.all(8), decoration: BoxDecoration( color: Colors.green.withOpacity(0.12), borderRadius: BorderRadius.circular(10), ), child: const Icon(Icons.mark_chat_read, color: Colors.green, size: 24), ), const SizedBox(width: 12), const Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Alertas por WhatsApp', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16), ), Text( 'Notificaciones vía Sigma-Robot Gateway', style: TextStyle(color: AppTheme.textSecondary, fontSize: 11), ), ], ), ), IconButton( icon: const Icon(Icons.close), onPressed: () => Navigator.pop(ctx), ), ], ), const SizedBox(height: 16), const Text( 'Código de país y número móvil:', style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: AppTheme.textPrimary), ), const SizedBox(height: 8), Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ // Selector de Código de País Container( padding: const EdgeInsets.symmetric(horizontal: 10), decoration: BoxDecoration( border: Border.all(color: Colors.grey.shade300), borderRadius: BorderRadius.circular(10), ), child: DropdownButtonHideUnderline( child: DropdownButton( value: codigoPais, items: PhoneUtils.paisesDisponibles.map((p) { return DropdownMenuItem( value: p.codigo, child: Text('${p.bandera} +${p.codigo}', style: const TextStyle(fontSize: 13)), ); }).toList(), onChanged: (nuevo) { if (nuevo != null) { setModalState(() => codigoPais = nuevo); } }, ), ), ), const SizedBox(width: 10), // Entrada de número de teléfono Expanded( child: TextFormField( controller: phoneCtrl, keyboardType: TextInputType.phone, decoration: InputDecoration( hintText: 'Ej. 0991234567', contentPadding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12), border: OutlineInputBorder(borderRadius: BorderRadius.circular(10)), suffixIcon: esValido ? const Icon(Icons.check_circle, color: Colors.green, size: 20) : null, ), onChanged: (_) => setModalState(() {}), ), ), ], ), const SizedBox(height: 14), // Previsualización y validación Regex en vivo Container( padding: const EdgeInsets.all(12), decoration: BoxDecoration( color: esValido ? Colors.green.shade50 : Colors.amber.shade50, borderRadius: BorderRadius.circular(10), border: Border.all(color: esValido ? Colors.green.shade200 : Colors.amber.shade200), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Icon( esValido ? Icons.verified : Icons.info_outline, size: 16, color: esValido ? Colors.green.shade700 : Colors.amber.shade800, ), const SizedBox(width: 6), Text( esValido ? 'Número normalizado para WhatsApp' : 'Formato incompleto', style: TextStyle( fontSize: 12, fontWeight: FontWeight.bold, color: esValido ? Colors.green.shade800 : Colors.amber.shade900, ), ), ], ), const SizedBox(height: 6), Text( normalizado.isNotEmpty ? 'Destino: +$normalizado (${paisActual.nombre})' : 'Ingresa tu número (se auto-formatea con código +$codigoPais)', style: TextStyle( fontSize: 12, color: esValido ? Colors.green.shade900 : Colors.grey.shade700, fontFamily: 'monospace', ), ), ], ), ), const SizedBox(height: 20), // Botones de acción: Probar Alerta y Guardar Row( children: [ Expanded( child: OutlinedButton.icon( icon: enviandoPrueba ? const SizedBox(width: 14, height: 14, child: CircularProgressIndicator(strokeWidth: 2)) : const Icon(Icons.send_outlined, size: 16), label: const Text('Probar Alerta', style: TextStyle(fontSize: 12)), onPressed: (!esValido || enviandoPrueba) ? null : () async { setModalState(() => enviandoPrueba = true); final res = await WhatsAppService.enviarAlertaPrueba( telefono: normalizado, nombreVendedor: vendedor.nombre, codigoPais: codigoPais, ); setModalState(() => enviandoPrueba = false); if (context.mounted) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text(res.ok ? '✅ Alerta enviada con éxito a +$normalizado' : '⚠️ No se pudo enviar: ${res.error}'), backgroundColor: res.ok ? Colors.green.shade700 : Colors.red.shade700, ), ); } }, ), ), const SizedBox(width: 10), Expanded( child: ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: AppTheme.primaryColor, foregroundColor: Colors.white, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), padding: const EdgeInsets.symmetric(vertical: 12), ), onPressed: !esValido ? null : () async { await provider.actualizarTelefonoVendedor(normalizado); if (context.mounted) { Navigator.pop(ctx); ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('Número de WhatsApp guardado: +$normalizado'), backgroundColor: Colors.green.shade700, ), ); } }, child: const Text('Guardar', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13)), ), ), ], ), ], ), ), ); }, ); }, ); } void _mostrarSelectorMoneda(BuildContext context, AppProvider provider) { showModalBottomSheet( context: context, shape: const RoundedRectangleBorder( borderRadius: BorderRadius.vertical(top: Radius.circular(20)), ), builder: (ctx) { return SafeArea( child: Column( mainAxisSize: MainAxisSize.min, children: [ const Padding( padding: EdgeInsets.fromLTRB(16, 20, 16, 8), child: Text('Selecciona la moneda', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16)), ), ...Moneda.disponibles.map((m) { final seleccionada = m.codigo == provider.moneda.codigo; return ListTile( leading: Text(m.simbolo, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: AppTheme.primaryColor)), title: Text(m.nombre, style: const TextStyle(fontSize: 14)), subtitle: Text(m.codigo, style: const TextStyle(fontSize: 11, color: AppTheme.textSecondary)), trailing: seleccionada ? const Icon(Icons.check_circle, color: AppTheme.successColor) : null, onTap: () { provider.setMoneda(m); Navigator.pop(ctx); }, ); }).toList(), const SizedBox(height: 8), ], ), ); }, ); } Widget _buildLogoutBtn(BuildContext context, AppProvider provider) { return SizedBox( width: double.infinity, height: 50, child: OutlinedButton.icon( icon: const Icon(Icons.logout, color: AppTheme.dangerColor), label: const Text('Cerrar sesión', style: TextStyle(color: AppTheme.dangerColor, fontWeight: FontWeight.w600)), style: OutlinedButton.styleFrom( side: const BorderSide(color: AppTheme.dangerColor), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), ), onPressed: () { showDialog( context: context, builder: (_) => AlertDialog( title: const Text('Cerrar sesión'), content: const Text('¿Seguro que deseas salir?'), actions: [ TextButton(onPressed: () => Navigator.pop(context), child: const Text('Cancelar')), TextButton( onPressed: () { Navigator.pop(context); provider.logout(); }, child: const Text('Salir', style: TextStyle(color: AppTheme.dangerColor)), ), ], ), ); }, ), ); } Widget _card({required Widget child}) { return Container( padding: const EdgeInsets.all(16), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(14), boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.04), blurRadius: 6)], ), child: child, ); } }