import 'dart:async';
import 'package:flutter/material.dart';
import 'package:supabase_flutter/supabase_flutter.dart'; 
import '../models/team_model.dart';
import '../models/person_model.dart';
import '../widgets/team_widgets.dart'; 
import '../widgets/stats_widgets.dart';

class TeamStatsPage extends StatefulWidget {
  final Team team;

  const TeamStatsPage({super.key, required this.team});

  @override
  State<TeamStatsPage> createState() => _TeamStatsPageState();
}

class _TeamStatsPageState extends State<TeamStatsPage> {
  final StatsController _controller = StatsController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF5F7FA),
      body: Column(
        children: [
          // Cabeçalho com informações da equipa
          StatsHeader(team: widget.team),
          
          Expanded(
            child: StreamBuilder<List<Person>>(
              // O StreamBuilder reconstrói a UI automaticamente sempre que o Supabase envia novos dados
              stream: _controller.getMembers(widget.team.id),
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return const Center(child: CircularProgressIndicator());
                }

                if (snapshot.hasError) {
                  return Center(child: Text("Erro ao carregar: ${snapshot.error}"));
                }

                final members = snapshot.data ?? [];
                
                // Filtros para organizar a lista
                final coaches = members.where((m) => m.type == 'Treinador').toList();
                final players = members.where((m) => m.type == 'Jogador').toList();

                return RefreshIndicator(
                  onRefresh: () async => setState(() {}), // Pull to refresh como backup
                  child: SingleChildScrollView(
                    physics: const AlwaysScrollableScrollPhysics(),
                    padding: const EdgeInsets.all(16.0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        StatsSummaryCard(total: members.length),
                        const SizedBox(height: 30),

                        // SECÇÃO TREINADORES
                        if (coaches.isNotEmpty) ...[
                          const StatsSectionTitle(title: "Treinadores"),
                          ...coaches.map((c) => PersonCard(
                                person: c,
                                isCoach: true,
                                onEdit: () => _controller.showEditPersonDialog(context, widget.team.id, c),
                                onDelete: () => _confirmDelete(context, c),
                              )),
                          const SizedBox(height: 30),
                        ],

                        // SECÇÃO JOGADORES
                        const StatsSectionTitle(title: "Jogadores"),
                        if (players.isEmpty)
                          const Padding(
                            padding: EdgeInsets.only(top: 20),
                            child: Text("Nenhum jogador nesta equipa.", 
                                style: TextStyle(color: Colors.grey, fontSize: 16)),
                          )
                        else
                          ...players.map((p) => PersonCard(
                                person: p,
                                isCoach: false,
                                onEdit: () => _controller.showEditPersonDialog(context, widget.team.id, p),
                                onDelete: () => _confirmDelete(context, p),
                              )),
                        const SizedBox(height: 80), // Espaço para o FAB não tapar o último card
                      ],
                    ),
                  ),
                );
              },
            ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        // Hero tag única para evitar o erro de tags duplicadas
        heroTag: 'fab_team_${widget.team.id}', 
        onPressed: () => _controller.showAddPersonDialog(context, widget.team.id),
        backgroundColor: const Color(0xFF00C853),
        child: const Icon(Icons.add, color: Colors.white),
      ),
    );
  }

  void _confirmDelete(BuildContext context, Person person) {
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text("Eliminar Membro?"),
        content: Text("Tens a certeza que queres remover ${person.name}?"),
        actions: [
          TextButton(onPressed: () => Navigator.pop(ctx), child: const Text("Cancelar")),
          TextButton(
            onPressed: () async {
              await _controller.deletePerson(person.id);
              if (ctx.mounted) Navigator.pop(ctx);
            },
            child: const Text("Eliminar", style: TextStyle(color: Colors.red)),
          ),
        ],
      ),
    );
  }
}

// --- CONTROLLER SUPABASE ---

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

  // 1. LER (A escuta em tempo real)
  Stream<List<Person>> getMembers(String teamId) {
    return _supabase
        .from('members')
        .stream(primaryKey: ['id']) // Garante que a PK na tabela é 'id'
        .eq('team_id', teamId)
        .order('name', ascending: true)
        .map((data) => data.map((json) => Person.fromMap(json)).toList());
  }

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

  // 3. DIÁLOGOS
  void showAddPersonDialog(BuildContext context, String teamId) {
    _showForm(context, teamId: teamId);
  }

  void showEditPersonDialog(BuildContext context, String teamId, Person person) {
    _showForm(context, teamId: teamId, person: person);
  }

  void _showForm(BuildContext context, {required String teamId, Person? person}) {
    final isEdit = person != null;
    final nameCtrl = TextEditingController(text: person?.name ?? '');
    final numCtrl = TextEditingController(text: person?.number ?? '');
    String selectedType = person?.type ?? 'Jogador';

    showDialog(
      context: context,
      builder: (ctx) => StatefulBuilder(
        builder: (ctx, setState) => AlertDialog(
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)),
          title: Text(isEdit ? "Editar Membro" : "Novo Membro"),
          content: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                TextField(
                  controller: nameCtrl,
                  decoration: const InputDecoration(labelText: "Nome Completo"),
                  textCapitalization: TextCapitalization.words,
                ),
                const SizedBox(height: 15),
                DropdownButtonFormField<String>(
                  value: selectedType,
                  decoration: const InputDecoration(labelText: "Função"),
                  items: ["Jogador", "Treinador"]
                      .map((e) => DropdownMenuItem(value: e, child: Text(e)))
                      .toList(),
                  onChanged: (v) {
                    if (v != null) setState(() => selectedType = v);
                  },  
                ),
                if (selectedType == "Jogador") ...[
                  const SizedBox(height: 15),
                  TextField(
                    controller: numCtrl,
                    decoration: const InputDecoration(labelText: "Número da Camisola"),
                    keyboardType: TextInputType.number,
                  ),
                ]
              ],
            ),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(ctx), 
              child: const Text("Cancelar")
            ),
            ElevatedButton(
              style: ElevatedButton.styleFrom(
                backgroundColor: const Color(0xFF00C853),
                shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8))
              ),
              onPressed: () async {
                if (nameCtrl.text.trim().isEmpty) return;

                String? numeroFinal = (selectedType == "Treinador") 
                    ? null 
                    : (numCtrl.text.trim().isEmpty ? null : numCtrl.text.trim());

                try {
                  if (isEdit) {
                    await _supabase.from('members').update({
                      'name': nameCtrl.text.trim(),
                      'type': selectedType,
                      'number': numeroFinal,
                    }).eq('id', person.id);
                  } else {
                    await _supabase.from('members').insert({
                      'team_id': teamId,
                      'name': nameCtrl.text.trim(),
                      'type': selectedType,
                      'number': numeroFinal,
                    });
                  }
                  if (ctx.mounted) Navigator.pop(ctx);
                } catch (e) {
                  debugPrint("Erro Supabase: $e");
                  if (ctx.mounted) {
                    ScaffoldMessenger.of(ctx).showSnackBar(
                      SnackBar(content: Text("Erro ao guardar: $e"), backgroundColor: Colors.red)
                    );
                  }
                }
              },
              child: const Text("Guardar", style: TextStyle(color: Colors.white)),
            )
          ],
        ),
      ),
    );
  }

  void dispose() {} 
}