import 'package:flutter/material.dart';
import 'package:supabase_flutter/supabase_flutter.dart';

class RegisterController extends ChangeNotifier {
  // Chave para identificar e validar o formulário
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();

  final nameController = TextEditingController();
  final emailController = TextEditingController();
  final passwordController = TextEditingController();
  final confirmPasswordController = TextEditingController(); // Novo campo

  bool isLoading = false;

  // --- AS TUAS VALIDAÇÕES ---
  String? validateEmail(String? value) {
    if (value == null || value.isEmpty) return 'Por favor, insira o seu email';
    final emailRegex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$');
    if (!emailRegex.hasMatch(value)) return 'Por favor, insira um email válido';
    return null;
  }

  String? validatePassword(String? value) {
    if (value == null || value.isEmpty) return 'Por favor, insira a sua password';
    if (value.length < 6) return 'A password deve ter pelo menos 6 caracteres';
    return null;
  }

  String? validateConfirmPassword(String? value) {
    if (value == null || value.isEmpty) {
      return 'Por favor, confirme a sua password';
    }
    if (value != passwordController.text) {
      return 'As passwords não coincidem';
    }
    return null;
  }
  // ---------------------------

  Future<void> signUp(BuildContext context) async {
    // 1. Verifica se o formulário é válido antes de fazer qualquer coisa
    if (!formKey.currentState!.validate()) {
      return; 
    }

    isLoading = true;
    notifyListeners();

    try {
      final AuthResponse res = await Supabase.instance.client.auth.signUp(
        email: emailController.text.trim(),
        password: passwordController.text.trim(),
        data: {'full_name': nameController.text.trim()},
      );

      final user = res.user;

      if (user != null && context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('Conta criada! Podes fazer login.')),
        );
        Navigator.pop(context);
      }
    } on AuthException catch (e) {
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text(e.message), backgroundColor: Colors.red),
        );
      }
    } catch (e) {
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('Erro inesperado'), backgroundColor: Colors.red),
        );
      }
    } finally {
      isLoading = false;
      notifyListeners();
    }
  }

  @override
  void dispose() {
    nameController.dispose();
    emailController.dispose();
    passwordController.dispose();
    confirmPasswordController.dispose();
    super.dispose();
  }
}