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';

// --- CABEÇALHO ---
class StatsHeader extends StatelessWidget {
  final Team team;

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

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.only(top: 50, left: 20, right: 20, bottom: 20),
      decoration: const BoxDecoration(
        color: Color(0xFF2C3E50),
        borderRadius: BorderRadius.only(bottomLeft: Radius.circular(30), bottomRight: Radius.circular(30)),
      ),
      child: Row(
        children: [
          IconButton(
            icon: const Icon(Icons.arrow_back, color: Colors.white),
            onPressed: () => Navigator.pop(context),
          ),
          const SizedBox(width: 10),
          
          // IMAGEM OU EMOJI DA EQUIPA AQUI!
          CircleAvatar(
            radius: 24,
            backgroundColor: Colors.white24,
            backgroundImage: (team.imageUrl.isNotEmpty && team.imageUrl.startsWith('http'))
                ? NetworkImage(team.imageUrl)
                : null,
            child: (team.imageUrl.isEmpty || !team.imageUrl.startsWith('http'))
                ? Text(
                    team.imageUrl.isEmpty ? "🛡️" : team.imageUrl,
                    style: const TextStyle(fontSize: 20),
                  )
                : null,
          ),
          
          const SizedBox(width: 15),
          Expanded( // Expanded evita overflow se o nome for muito longo
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(team.name, style: const TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold), overflow: TextOverflow.ellipsis),
                Text(team.season, style: const TextStyle(color: Colors.white70, fontSize: 14)),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

// --- CARD DE RESUMO ---
class StatsSummaryCard extends StatelessWidget {
  final int total;

  const StatsSummaryCard({super.key, required this.total});

  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: 4,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
      child: Container(
        padding: const EdgeInsets.all(20),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(20),
          gradient: LinearGradient(colors: [Colors.blue.shade700, Colors.blue.shade400]),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            const Text("Total de Membros", style: TextStyle(color: Colors.white, fontSize: 16)),
            Text("$total", style: const TextStyle(color: Colors.white, fontSize: 28, fontWeight: FontWeight.bold)),
          ],
        ),
      ),
    );
  }
}

// --- TÍTULO DE SECÇÃO ---
class StatsSectionTitle extends StatelessWidget {
  final String title;

  const StatsSectionTitle({super.key, required this.title});

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(title, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: Color(0xFF2C3E50))),
        const Divider(),
      ],
    );
  }
}

// --- CARD DA PESSOA (JOGADOR/TREINADOR) ---
class PersonCard extends StatelessWidget {
  final Person person;
  final bool isCoach;
  final VoidCallback onEdit;
  final VoidCallback onDelete;

  const PersonCard({
    super.key,
    required this.person,
    required this.isCoach,
    required this.onEdit,
    required this.onDelete,
  });

  @override
  Widget build(BuildContext context) {
    return Card(
      margin: const EdgeInsets.only(top: 12),
      elevation: 2,
      color: isCoach ? const Color(0xFFFFF9C4) : Colors.white,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)),
      child: ListTile(
        leading: isCoach
            ? const CircleAvatar(backgroundColor: Colors.orange, child: Icon(Icons.person, color: Colors.white))  
            : Container(
                width: 45,
                height: 45,
                alignment: Alignment.center,
                decoration: BoxDecoration(color: Colors.blue.withOpacity(0.1), borderRadius: BorderRadius.circular(10)),
                child: Text(person.number ?? "J", style: const TextStyle(color: Colors.blue, fontWeight: FontWeight.bold, fontSize: 16)),
              ),
        title: Text(person.name, style: const TextStyle(fontWeight: FontWeight.bold)),
        
        // --- CANTO DIREITO (Trailing) ---
        trailing: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            // IMAGEM DA EQUIPA NO CARD DO JOGADOR

            const SizedBox(width: 5), // Espaço
            
            IconButton(
              icon: const Icon(Icons.edit_outlined, color: Colors.blue),
              onPressed: onEdit,
            ),
            IconButton(
              icon: const Icon(Icons.delete_outline, color: Colors.red),
              onPressed: onDelete,
            ),
          ],
        ),
      ),
    );
  }
}

// ==========================================
// 2. PÁGINA PRINCIPAL
// ==========================================

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
          StatsHeader(team: widget.team),
          
          Expanded(
            child: StreamBuilder<List<Person>>(
              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 ?? [];
                
                final coaches = members.where((m) => m.type == 'Treinador').toList();
                final players = members.where((m) => m.type == 'Jogador').toList();

                return RefreshIndicator(
                  onRefresh: () async => setState(() {}),
                  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),

                        // 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),
                        ],

                        // 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),
                      ],
                    ),
                  ),
                );
              },
            ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        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)),
          ),
        ],
      ),
    );
  }
}

// ==========================================
// 3. CONTROLLER
// ==========================================

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

  Stream<List<Person>> getMembers(String teamId) {
    return _supabase
        .from('members')
        .stream(primaryKey: ['id'])
        .eq('team_id', teamId)
        .order('name', ascending: true)
        .map((data) => data.map((json) => Person.fromMap(json)).toList());
  }

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

  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) {
                    String errorMsg = "Erro ao guardar: $e";
                    if (e.toString().contains('unique')) {
                      errorMsg = "Já existe um membro com este numero na equipa.";
                    }
                    ScaffoldMessenger.of(ctx).showSnackBar(
                      SnackBar(content: Text(errorMsg), backgroundColor: Colors.red)
                    );
                  }
                }
              },
              child: const Text("Guardar", style: TextStyle(color: Colors.white)),
            )
          ],
        ),
      ),
    );
  }
}