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

class StatsController {
  final SupabaseClient _supabase = Supabase.instance.client;

  // --- 1. LER MEMBROS (STREAM EM TEMPO REAL) ---
  Stream<List<Person>> getMembers(String teamId) {
    return _supabase
        .from('members') // Nome da tua tabela no Supabase
        .stream(primaryKey: ['id'])
        .eq('team_id', teamId)
        .order('name', ascending: true)
        .map((data) => data.map((json) => Person.fromMap(json)).toList());
  }

  // --- 2. APAGAR ---
  Future<void> deletePerson(String teamId, String personId) async {
    try {
      await _supabase.from('members').delete().eq('id', personId);
    } catch (e) {
      debugPrint("Erro ao eliminar: $e");
    }
  }

  // --- 3. DIÁLOGOS DE ADICIONAR / EDITAR ---

  // Abrir diálogo para criar novo
  void showAddPersonDialog(BuildContext context, String teamId) {
    _showPersonForm(context, teamId: teamId);
  }

  // Abrir diálogo para editar existente
  void showEditPersonDialog(BuildContext context, String teamId, Person person) {
    _showPersonForm(context, teamId: teamId, person: person);
  }

  // Lógica interna do formulário
  void _showPersonForm(BuildContext context, {required String teamId, Person? person}) {
    final isEditing = person != null;
    
    // Controladores de texto
    final nameController = TextEditingController(text: person?.name ?? '');
    final numberController = TextEditingController(text: person?.number ?? '');
    
    // Variável para o Dropdown (Valor inicial)
    String selectedType = person?.type ?? 'Jogador';

    showDialog(
      context: context,
      builder: (context) {
        // StatefulBuilder serve para atualizar o Dropdown DENTRO do diálogo
        return StatefulBuilder(
          builder: (context, setState) {
            return AlertDialog(
              title: Text(isEditing ? 'Editar Membro' : 'Novo Membro'),
              content: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  // Nome
                  TextField(
                    controller: nameController,
                    decoration: const InputDecoration(labelText: 'Nome'),
                    textCapitalization: TextCapitalization.sentences,
                  ),
                  const SizedBox(height: 10),
                  
                  // Tipo (Jogador vs Treinador)
                  DropdownButtonFormField<String>(
                    value: selectedType,
                    decoration: const InputDecoration(labelText: 'Função'),
                    items: const [
                      DropdownMenuItem(value: 'Jogador', child: Text('Jogador')),
                      DropdownMenuItem(value: 'Treinador', child: Text('Treinador')),
                    ],
                    onChanged: (value) {
                      if (value != null) {
                        setState(() => selectedType = value);
                      }
                    },
                  ),
                  const SizedBox(height: 10),

                  // Número (Só mostramos se for Jogador)
                  if (selectedType == 'Jogador')
                    TextField(
                      controller: numberController,
                      decoration: const InputDecoration(labelText: 'Número da Camisola'),
                      keyboardType: TextInputType.number,
                    ),
                ],
              ),
              actions: [
                TextButton(
                  onPressed: () => Navigator.pop(context),
                  child: const Text('Cancelar'),
                ),
                ElevatedButton(
                  style: ElevatedButton.styleFrom(backgroundColor: const Color(0xFF00C853)),
                  onPressed: () async {
                    if (nameController.text.trim().isEmpty) return;

                    final name = nameController.text.trim();
                    final number = numberController.text.trim();

                    if (isEditing) {
                      // ATUALIZAR
                      await _supabase.from('members').update({
                        'name': name,
                        'type': selectedType,
                        'number': number,
                      }).eq('id', person!.id);
                    } else {
                      // CRIAR NOVO
                      await _supabase.from('members').insert({
                        'team_id': teamId,
                        'name': name,
                        'type': selectedType,
                        'number': number,
                      });
                    }
                    
                    if (context.mounted) Navigator.pop(context);
                  },
                  child: Text(isEditing ? 'Guardar' : 'Adicionar', style: const TextStyle(color: Colors.white)),
                ),
              ],
            );
          },
        );
      },
    );
  }
}