import 'package:flutter/material.dart'; import 'package:supabase_flutter/supabase_flutter.dart'; import 'dart:async'; import '../main.dart' show supabase; Future showRegisterSheet(BuildContext context) { return showModalBottomSheet( context: context, isScrollControlled: true, showDragHandle: true, backgroundColor: const Color(0xFFFFE6F1), shape: const RoundedRectangleBorder( borderRadius: BorderRadius.vertical(top: Radius.circular(24)), ), builder: (ctx) => const RegisterBottomSheet(), ); } class RegisterBottomSheet extends StatefulWidget { const RegisterBottomSheet({super.key}); @override State createState() => _RegisterBottomSheetState(); } class _RegisterBottomSheetState extends State { final _formKey = GlobalKey(); final _nameController = TextEditingController(); final _emailController = TextEditingController(); final _passwordController = TextEditingController(); bool _loading = false; Future _persistRegistrationData({ required String uid, required String name, required String email, }) async { await supabase.from('profiles').upsert({ 'id': uid, 'name': name, 'email': email, }).timeout(const Duration(seconds: 20)); } @override void dispose() { _nameController.dispose(); _emailController.dispose(); _passwordController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { final bottomInset = MediaQuery.viewInsetsOf(context).bottom; return SafeArea( child: Padding( padding: EdgeInsets.fromLTRB(18, 6, 18, 18 + bottomInset), child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ const Text( 'Criar conta', textAlign: TextAlign.center, style: TextStyle( fontSize: 18, fontWeight: FontWeight.w900, color: Color(0xFFFF55A7), ), ), const SizedBox(height: 12), Container( padding: const EdgeInsets.all(14), decoration: BoxDecoration( color: Colors.white.withValues(alpha: 0.82), borderRadius: BorderRadius.circular(16), border: Border.all(color: Colors.black.withValues(alpha: 0.08)), ), child: Form( key: _formKey, child: Column( mainAxisSize: MainAxisSize.min, children: [ TextFormField( controller: _nameController, textInputAction: TextInputAction.next, decoration: const InputDecoration(labelText: 'Nome'), validator: (v) { if (v == null || v.trim().isEmpty) { return 'Informe seu nome'; } if (v.trim().length < 2) { return 'Nome muito curto'; } return null; }, ), TextFormField( controller: _emailController, keyboardType: TextInputType.emailAddress, textInputAction: TextInputAction.next, decoration: const InputDecoration(labelText: 'Email'), validator: (v) { final value = (v ?? '').trim(); if (value.isEmpty) return 'Informe seu email'; if (!value.contains('@')) return 'Email inválido'; return null; }, ), TextFormField( controller: _passwordController, obscureText: true, textInputAction: TextInputAction.done, decoration: const InputDecoration(labelText: 'Senha'), validator: (v) { final value = (v ?? ''); if (value.isEmpty) return 'Informe sua senha'; if (value.length < 6) return 'Mínimo de 6 caracteres'; return null; }, ), ], ), ), ), const SizedBox(height: 14), Row( children: [ Expanded( child: SizedBox( height: 44, child: TextButton( onPressed: _loading ? null : () => Navigator.of(context).pop(), child: const Text('Cancelar'), ), ), ), const SizedBox(width: 10), Expanded( child: SizedBox( height: 44, child: FilledButton( style: FilledButton.styleFrom( backgroundColor: const Color(0xFF2F9E94), foregroundColor: Colors.white, shape: const StadiumBorder(), textStyle: const TextStyle(fontWeight: FontWeight.w900), ), onPressed: _loading ? null : _submit, child: _loading ? const SizedBox( width: 18, height: 18, child: CircularProgressIndicator( strokeWidth: 2, color: Colors.white, ), ) : const Text('Registrar'), ), ), ), ], ), ], ), ), ); } Future _submit() async { if (!(_formKey.currentState?.validate() ?? false)) return; setState(() => _loading = true); try { final name = _nameController.text.trim(); final email = _emailController.text.trim(); final password = _passwordController.text; final response = await supabase.auth .signUp( email: email, password: password, data: {'name': name}, ) .timeout(const Duration(seconds: 20)); final user = response.user; if (user == null) { throw StateError('Usuário não encontrado após criar conta.'); } final uid = user.id; if (!mounted) return; // Fecha o sheet imediatamente após autenticar. // As gravações no banco seguem em background para não travar a UI. Navigator.of(context).pop(); unawaited( _persistRegistrationData( uid: uid, name: name, email: email, ).catchError((_) {}), ); } on AuthException catch (e) { if (!mounted) return; ScaffoldMessenger.of( context, ).showSnackBar(SnackBar(content: Text(_friendlyAuthError(e)))); } on TimeoutException { if (!mounted) return; ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text( 'Tempo esgotado. Verifique sua conexão e tente novamente.', ), ), ); } catch (e) { if (!mounted) return; ScaffoldMessenger.of( context, ).showSnackBar(SnackBar(content: Text('Erro: $e'))); } finally { if (mounted && _loading) setState(() => _loading = false); } } String _friendlyAuthError(AuthException e) { switch (e.code) { case 'email_exists': case 'user_already_exists': return 'Este email já está em uso.'; case 'weak_password': return 'Senha fraca. Use pelo menos 6 caracteres.'; default: return e.message; } } }