import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import '../../services/auth_service.dart'; import '../../widgets/password_strength_indicator.dart'; const _kBg = Color(0xFF0A1E3C); const _kTopBar = Color(0xFF0D2D6B); const _kPanel = Color(0xFF0F2A4A); const _kCard = Color(0xFF163558); const _kBorder = Color(0xFF1E4070); const _kAccent = Color(0xFF1976D2); const _kTextMuted = Color(0xFFAABBCC); const _kError = Color(0xFFFF6B6B); const _kSuccess = Color(0xFF2E7D32); class RegistroCloudScreen extends StatefulWidget { const RegistroCloudScreen({Key? key}) : super(key: key); @override State createState() => _RegistroCloudScreenState(); } class _RegistroCloudScreenState extends State { int _paso = 0; // 0=Datos, 1=OTP, 2=Cuenta, 3=Creando, 4=Éxito // Paso 1 final _form1Key = GlobalKey(); final _nombreCtrl = TextEditingController(); final _ciCtrl = TextEditingController(); final _emailCtrl = TextEditingController(); final _telCtrl = TextEditingController(); final _ciudadCtrl = TextEditingController(); final _dirCtrl = TextEditingController(); // Paso 2 final _otpCtrl = TextEditingController(); int _cooldown = 60; Timer? _timer; String _usrToken = ''; // Paso 3 final _form3Key = GlobalKey(); final _empresaCtrl = TextEditingController(); final _usuarioCtrl = TextEditingController(); final _passCtrl = TextEditingController(); final _confirmCtrl = TextEditingController(); bool _obscurePass = true; bool _obscureConfirm = true; // Animación creación int _creandoPaso = 0; double _creandoProgress = 0; final _creandoPasos = [ 'Registrando usuario...', 'Creando empresa en la nube...', 'Construyendo base de datos...', 'Configurando tablas...', 'Aplicando configuración...', 'Finalizando...', ]; final _creandoDuraciones = [2, 3, 10, 7, 5, 3]; bool _loading = false; String? _error; @override void dispose() { _nombreCtrl.dispose(); _ciCtrl.dispose(); _emailCtrl.dispose(); _telCtrl.dispose(); _ciudadCtrl.dispose(); _dirCtrl.dispose(); _otpCtrl.dispose(); _empresaCtrl.dispose(); _usuarioCtrl.dispose(); _passCtrl.dispose(); _confirmCtrl.dispose(); _timer?.cancel(); super.dispose(); } // ── Paso 1: pre-register ────────────────────────────────────── Future _continuar() async { if (!(_form1Key.currentState?.validate() ?? false)) return; setState(() { _loading = true; _error = null; }); try { await AuthService.preRegister( nombre: _nombreCtrl.text.trim(), email: _emailCtrl.text.trim(), telefono: _telCtrl.text.trim(), direccion: _dirCtrl.text.trim(), ci: _ciCtrl.text.trim(), ciudad: _ciudadCtrl.text.trim(), ); _startCooldown(); setState(() { _paso = 1; _loading = false; }); } on AuthException catch (e) { setState(() { _error = e.message; _loading = false; }); } catch (_) { setState(() { _error = 'Sin conexión. Verifica tu internet e intenta de nuevo.'; _loading = false; }); } } // ── Paso 2: verificar OTP ───────────────────────────────────── void _startCooldown() { _cooldown = 60; _timer?.cancel(); _timer = Timer.periodic(const Duration(seconds: 1), (t) { if (!mounted) { t.cancel(); return; } setState(() { if (_cooldown > 0) { _cooldown--; } else { t.cancel(); } }); }); } Future _verificarOtp() async { final code = _otpCtrl.text.trim(); if (code.length != 6) { setState(() => _error = 'Ingresa el código de 6 dígitos.'); return; } setState(() { _loading = true; _error = null; }); try { _usrToken = await AuthService.verifyOtpRegistro( email: _emailCtrl.text.trim(), codigo: code, ); setState(() { _paso = 2; _loading = false; }); } on AuthException catch (e) { setState(() { _error = e.message; _loading = false; }); } catch (_) { setState(() { _error = 'Error de conexión al verificar.'; _loading = false; }); } } Future _reenviar() async { if (_cooldown > 0) return; setState(() { _loading = true; _error = null; }); try { await AuthService.preRegister( nombre: _nombreCtrl.text.trim(), email: _emailCtrl.text.trim(), telefono: _telCtrl.text.trim(), direccion: _dirCtrl.text.trim(), ); _startCooldown(); } catch (_) { setState(() => _error = 'Error al reenviar el código.'); } setState(() => _loading = false); } // ── Paso 3: register ────────────────────────────────────────── Future _crearCuenta() async { if (!(_form3Key.currentState?.validate() ?? false)) return; setState(() { _paso = 3; _loading = true; _error = null; }); _animarCreacion(); try { await AuthService.register( nombre: _nombreCtrl.text.trim(), usuario: _usuarioCtrl.text.trim().toLowerCase(), password: _passCtrl.text, dba: _empresaCtrl.text.trim(), email: _emailCtrl.text.trim(), usrToken: _usrToken.isNotEmpty ? _usrToken : null, ); if (mounted) setState(() { _paso = 4; _loading = false; }); } on AuthException catch (e) { if (mounted) { setState(() { _paso = 2; _error = e.message; _loading = false; }); } } catch (_) { if (mounted) { setState(() { _paso = 2; _error = 'Error de conexión al crear la cuenta.'; _loading = false; }); } } } void _animarCreacion() async { double total = _creandoDuraciones.fold(0, (s, d) => s + d).toDouble(); double elapsed = 0; for (int i = 0; i < _creandoDuraciones.length; i++) { if (!mounted) return; setState(() => _creandoPaso = i); await Future.delayed(Duration(seconds: _creandoDuraciones[i])); elapsed += _creandoDuraciones[i]; if (!mounted) return; setState(() => _creandoProgress = elapsed / total); } } // ── Build ───────────────────────────────────────────────────── @override Widget build(BuildContext context) { return Scaffold( backgroundColor: _kBg, body: Stack( children: [ Container( height: 160, decoration: const BoxDecoration( gradient: LinearGradient( colors: [_kTopBar, _kBg], begin: Alignment.topCenter, end: Alignment.bottomCenter, ), ), ), SafeArea( child: Column( children: [ _buildTopBar(), if (_paso < 3) _buildStepper(), Expanded( child: SingleChildScrollView( child: _buildContent(), ), ), ], ), ), ], ), ); } Widget _buildTopBar() { return Padding( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), child: Row( children: [ IconButton( icon: const Icon(Icons.arrow_back, color: Colors.white), onPressed: _paso == 0 || _paso >= 3 ? () => Navigator.pop(context) : () => setState(() { _paso--; _error = null; }), ), const Text( 'Crear cuenta en la nube', style: TextStyle( color: Colors.white, fontSize: 17, fontWeight: FontWeight.w600), ), ], ), ); } Widget _buildStepper() { return Padding( padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 8), child: Row( children: List.generate(3, (i) { final done = _paso > i; final active = _paso == i; return Expanded( child: Row( children: [ _stepCircle(i + 1, done, active), if (i < 2) Expanded( child: Container( height: 2, color: done ? _kAccent : _kBorder, ), ), ], ), ); }), ), ); } Widget _stepCircle(int num, bool done, bool active) { return Column( children: [ Container( width: 28, height: 28, decoration: BoxDecoration( shape: BoxShape.circle, color: done || active ? _kAccent : Colors.transparent, border: done || active ? null : Border.all(color: _kBorder, width: 1.5), ), child: Center( child: done ? const Icon(Icons.check, color: Colors.white, size: 14) : Text( '$num', style: TextStyle( color: active ? Colors.white : _kTextMuted, fontSize: 12, fontWeight: FontWeight.bold, ), ), ), ), const SizedBox(height: 2), Text( ['Datos', 'Verificar', 'Cuenta'][num - 1], style: TextStyle( color: active ? Colors.white : _kTextMuted, fontSize: 10, ), ), ], ); } Widget _buildContent() { return Container( width: double.infinity, constraints: BoxConstraints( minHeight: MediaQuery.of(context).size.height - 160, ), decoration: const BoxDecoration( color: _kPanel, borderRadius: BorderRadius.only( topLeft: Radius.circular(32), topRight: Radius.circular(32), ), ), padding: const EdgeInsets.fromLTRB(24, 28, 24, 40), child: () { switch (_paso) { case 0: return _buildPaso1(); case 1: return _buildPaso2(); case 2: return _buildPaso3(); case 3: return _buildCreando(); case 4: return _buildExito(); default: return const SizedBox.shrink(); } }(), ); } // ── Paso 1 UI ───────────────────────────────────────────────── Widget _buildPaso1() { return Form( key: _form1Key, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ _sectionLabel('DATOS PERSONALES'), const SizedBox(height: 14), _field(_nombreCtrl, 'Nombre completo *', Icons.person_outline, validator: _req), const SizedBox(height: 13), _field(_ciCtrl, 'Cédula / RUC', Icons.tag_outlined, keyboardType: TextInputType.number, inputFormatters: [FilteringTextInputFormatter.digitsOnly]), const SizedBox(height: 13), _field(_emailCtrl, 'Correo electrónico *', Icons.email_outlined, keyboardType: TextInputType.emailAddress, validator: _emailVal), const SizedBox(height: 13), _field(_telCtrl, 'Teléfono / Celular *', Icons.phone_outlined, keyboardType: TextInputType.phone, inputFormatters: [FilteringTextInputFormatter.digitsOnly], validator: _req), const SizedBox(height: 13), _field(_ciudadCtrl, 'Ciudad', Icons.location_city_outlined), const SizedBox(height: 13), _field(_dirCtrl, 'Dirección *', Icons.home_outlined, validator: _req), if (_error != null) ...[ const SizedBox(height: 14), _errorBox(_error!), ], const SizedBox(height: 24), _boton('CONTINUAR →', _loading ? null : _continuar), ], ), ); } // ── Paso 2 UI ───────────────────────────────────────────────── Widget _buildPaso2() { final email = _emailCtrl.text.trim(); final masked = email.contains('@') ? '${email.substring(0, 2)}***@${email.split('@').last}' : email; return Column( children: [ const SizedBox(height: 16), const Icon(Icons.mark_email_unread_outlined, size: 64, color: _kAccent), const SizedBox(height: 16), const Text( 'Revisa tu correo', style: TextStyle( color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold), ), const SizedBox(height: 8), Text( 'Enviamos un código de 6 dígitos a\n$masked', textAlign: TextAlign.center, style: const TextStyle(color: _kTextMuted, fontSize: 13), ), const SizedBox(height: 28), TextFormField( controller: _otpCtrl, keyboardType: TextInputType.number, textAlign: TextAlign.center, maxLength: 6, inputFormatters: [FilteringTextInputFormatter.digitsOnly], style: const TextStyle( color: Colors.white, fontSize: 28, letterSpacing: 12, fontWeight: FontWeight.bold), decoration: InputDecoration( hintText: '------', hintStyle: const TextStyle( color: _kBorder, fontSize: 28, letterSpacing: 12), counterText: '', filled: true, fillColor: _kCard, contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(12), borderSide: const BorderSide(color: _kBorder)), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(12), borderSide: const BorderSide(color: _kAccent, width: 2)), ), ), if (_error != null) ...[ const SizedBox(height: 14), _errorBox(_error!), ], const SizedBox(height: 24), _boton('VERIFICAR CÓDIGO ✓', _loading ? null : _verificarOtp), const SizedBox(height: 16), GestureDetector( onTap: _cooldown == 0 ? _reenviar : null, child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon(Icons.refresh, color: _cooldown == 0 ? _kAccent : _kTextMuted, size: 16), const SizedBox(width: 6), Text( _cooldown == 0 ? 'Reenviar código' : 'Reenviar en ${_cooldown}s', style: TextStyle( color: _cooldown == 0 ? _kAccent : _kTextMuted, fontSize: 13, ), ), ], ), ), ], ); } // ── Paso 3 UI ───────────────────────────────────────────────── Widget _buildPaso3() { return Form( key: _form3Key, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ _sectionLabel('DATOS DE LA EMPRESA'), const SizedBox(height: 14), TextFormField( controller: _empresaCtrl, validator: _req, style: const TextStyle(color: Colors.white, fontSize: 14), inputFormatters: [_EmpresaFormatter()], decoration: _deco('Nombre de la empresa *', Icons.business_outlined), ), const SizedBox(height: 22), _sectionLabel('USUARIO Y CONTRASEÑA'), const SizedBox(height: 14), _field(_usuarioCtrl, 'Nombre de usuario *', Icons.alternate_email, validator: (v) { if (v == null || v.trim().isEmpty) return 'Obligatorio'; if (v.trim().length < 3) return 'Mínimo 3 caracteres'; if (v.trim().length > 16) return 'Máximo 16 caracteres'; if (v.contains(' ')) return 'Sin espacios'; return null; }), const SizedBox(height: 13), TextFormField( controller: _passCtrl, obscureText: _obscurePass, validator: (v) { if (v == null || v.isEmpty) return 'Obligatorio'; if (v.length < 8) return 'Mínimo 8 caracteres'; return null; }, style: const TextStyle(color: Colors.white, fontSize: 14), decoration: _deco('Contraseña *', Icons.lock_outline).copyWith( suffixIcon: IconButton( icon: Icon( _obscurePass ? Icons.visibility_outlined : Icons.visibility_off_outlined, color: _kTextMuted, size: 20, ), onPressed: () => setState(() => _obscurePass = !_obscurePass), ), ), ), ValueListenableBuilder( valueListenable: _passCtrl, builder: (_, val, __) => PasswordStrengthIndicator(password: val.text), ), const SizedBox(height: 13), TextFormField( controller: _confirmCtrl, obscureText: _obscureConfirm, validator: (v) { if (v == null || v.isEmpty) return 'Obligatorio'; if (v != _passCtrl.text) return 'Las contraseñas no coinciden'; return null; }, style: const TextStyle(color: Colors.white, fontSize: 14), decoration: _deco('Confirmar contraseña *', Icons.lock_outline).copyWith( suffixIcon: IconButton( icon: Icon( _obscureConfirm ? Icons.visibility_outlined : Icons.visibility_off_outlined, color: _kTextMuted, size: 20, ), onPressed: () => setState(() => _obscureConfirm = !_obscureConfirm), ), ), ), if (_error != null) ...[ const SizedBox(height: 14), _errorBox(_error!), ], const SizedBox(height: 24), _boton('CREAR CUENTA EN LA NUBE ☁', _loading ? null : _crearCuenta), const SizedBox(height: 12), Center( child: TextButton( onPressed: () => Navigator.pop(context), child: const Text('Cancelar', style: TextStyle(color: _kTextMuted, fontSize: 13)), ), ), ], ), ); } // ── Pantalla "Creando" ──────────────────────────────────────── Widget _buildCreando() { return Column( children: [ const SizedBox(height: 16), ClipRRect( borderRadius: BorderRadius.circular(8), child: LinearProgressIndicator( value: _creandoProgress, backgroundColor: _kBorder, valueColor: const AlwaysStoppedAnimation(_kAccent), minHeight: 6, ), ), const SizedBox(height: 4), Align( alignment: Alignment.centerRight, child: Text( '${(_creandoProgress * 100).toInt()}%', style: const TextStyle(color: _kTextMuted, fontSize: 11), ), ), const SizedBox(height: 28), const Icon(Icons.cloud_outlined, size: 64, color: _kAccent), const SizedBox(height: 16), Text( _creandoPasos[_creandoPaso], style: const TextStyle( color: Colors.white, fontSize: 16, fontWeight: FontWeight.w600), ), const SizedBox(height: 6), const Text( 'Esto puede tomar un minuto.\nNo cierres la aplicación.', textAlign: TextAlign.center, style: TextStyle(color: _kTextMuted, fontSize: 13), ), const SizedBox(height: 28), ...List.generate(_creandoPasos.length, (i) { final done = i < _creandoPaso; final active = i == _creandoPaso; return Padding( padding: const EdgeInsets.symmetric(vertical: 4), child: Row( children: [ SizedBox( width: 20, height: 20, child: done ? const Icon(Icons.check_circle, color: _kSuccess, size: 18) : active ? const SizedBox( width: 16, height: 16, child: CircularProgressIndicator( strokeWidth: 2, color: _kAccent)) : const Icon(Icons.circle_outlined, color: _kBorder, size: 18), ), const SizedBox(width: 10), Text( _creandoPasos[i], style: TextStyle( color: done ? _kSuccess : active ? Colors.white : _kTextMuted, fontSize: 13, ), ), ], ), ); }), ], ); } // ── Pantalla Éxito ──────────────────────────────────────────── Widget _buildExito() { return Column( children: [ const SizedBox(height: 32), Container( width: 80, height: 80, decoration: const BoxDecoration( shape: BoxShape.circle, color: _kSuccess), child: const Icon(Icons.cloud_done_outlined, color: Colors.white, size: 40), ), const SizedBox(height: 24), const Text( '¡Cuenta creada!', style: TextStyle( color: Colors.white, fontSize: 22, fontWeight: FontWeight.bold), ), const SizedBox(height: 10), const Text( 'Tu empresa ya está activa\nen la nube. Ya puedes\niniciar sesión.', textAlign: TextAlign.center, style: TextStyle(color: _kTextMuted, fontSize: 14, height: 1.5), ), const SizedBox(height: 36), _boton('IR AL LOGIN', () { Navigator.pushNamedAndRemoveUntil( context, '/login', (_) => false); }), ], ); } // ── Helpers UI ──────────────────────────────────────────────── Widget _sectionLabel(String text) => Text( text, style: const TextStyle( color: _kAccent, fontSize: 11, fontWeight: FontWeight.bold, letterSpacing: 1.5, ), ); Widget _field( TextEditingController ctrl, String label, IconData icon, { TextInputType? keyboardType, List? inputFormatters, String? Function(String?)? validator, }) { return TextFormField( controller: ctrl, keyboardType: keyboardType, inputFormatters: inputFormatters, validator: validator, style: const TextStyle(color: Colors.white, fontSize: 14), decoration: _deco(label, icon), ); } InputDecoration _deco(String label, IconData icon) => InputDecoration( labelText: label, labelStyle: const TextStyle(color: _kTextMuted, fontSize: 13), prefixIcon: Icon(icon, color: _kTextMuted, size: 20), filled: true, fillColor: _kCard, contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(12), borderSide: const BorderSide(color: _kBorder)), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(12), borderSide: const BorderSide(color: _kAccent, width: 2)), errorBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(12), borderSide: const BorderSide(color: _kError)), focusedErrorBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(12), borderSide: const BorderSide(color: _kError, width: 2)), errorStyle: const TextStyle(color: _kError, fontSize: 11), ); Widget _errorBox(String msg) => Container( width: double.infinity, padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), decoration: BoxDecoration( color: _kError.withOpacity(0.10), borderRadius: BorderRadius.circular(8), border: Border.all(color: _kError.withOpacity(0.35)), ), child: Row( children: [ const Icon(Icons.error_outline, color: _kError, size: 16), const SizedBox(width: 8), Expanded( child: Text(msg, style: const TextStyle(fontSize: 12, color: _kError))), ], ), ); Widget _boton(String label, VoidCallback? onPressed) => SizedBox( width: double.infinity, height: 52, child: DecoratedBox( decoration: BoxDecoration( gradient: onPressed == null ? null : const LinearGradient( colors: [_kTopBar, _kAccent], begin: Alignment.centerLeft, end: Alignment.centerRight), color: onPressed == null ? _kBorder : null, borderRadius: BorderRadius.circular(12), boxShadow: onPressed == null ? const [] : [ BoxShadow( color: _kAccent.withOpacity(0.4), blurRadius: 12, offset: const Offset(0, 4)) ], ), child: ElevatedButton( onPressed: onPressed, style: ElevatedButton.styleFrom( primary: Colors.transparent, onPrimary: Colors.white, shadowColor: Colors.transparent, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12)), ), child: _loading && onPressed == null ? const SizedBox( width: 22, height: 22, child: CircularProgressIndicator( strokeWidth: 2.5, color: Colors.white)) : Text( label, style: const TextStyle( fontSize: 14, fontWeight: FontWeight.bold, letterSpacing: 1.0), ), ), ), ); String? _req(String? v) => (v == null || v.trim().isEmpty) ? 'Obligatorio' : null; String? _emailVal(String? v) { if (v == null || v.trim().isEmpty) return 'Obligatorio'; if (!v.contains('@') || !v.contains('.')) return 'Correo inválido'; return null; } } // ── Formatter: normaliza nombre de empresa en tiempo real ──────── class _EmpresaFormatter extends TextInputFormatter { static const _map = { 'á': 'A', 'à': 'A', 'ä': 'A', 'â': 'A', 'Á': 'A', 'À': 'A', 'Ä': 'A', 'é': 'E', 'è': 'E', 'ë': 'E', 'ê': 'E', 'É': 'E', 'È': 'E', 'Ë': 'E', 'í': 'I', 'ì': 'I', 'ï': 'I', 'î': 'I', 'Í': 'I', 'Ì': 'I', 'Ï': 'I', 'ó': 'O', 'ò': 'O', 'ö': 'O', 'ô': 'O', 'Ó': 'O', 'Ò': 'O', 'Ö': 'O', 'ú': 'U', 'ù': 'U', 'ü': 'U', 'û': 'U', 'Ú': 'U', 'Ù': 'U', 'Ü': 'U', 'ñ': 'N', 'Ñ': 'N', ' ': '_', '-': '_', }; @override TextEditingValue formatEditUpdate( TextEditingValue oldValue, TextEditingValue newValue) { final buf = StringBuffer(); for (final ch in newValue.text.characters) { final mapped = _map[ch] ?? ch.toUpperCase(); if (RegExp(r'^[A-Z0-9_]$').hasMatch(mapped)) buf.write(mapped); } final result = buf.toString(); return newValue.copyWith( text: result, selection: TextSelection.collapsed(offset: result.length), ); } }