import 'package:flutter/material.dart';
import 'package:playmaker/controllers/team_controller.dart';
import 'dart:async';
import '../models/team_model.dart';
import '../models/person_model.dart';
import '../controllers/team_controllers.dart'; // Para aceder à lista estática de membros

class TeamStatsPage extends StatelessWidget {
  final Team team;
  final StatsController _controller = StatsController();

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF5F7FA),
      body: Column(
        children: [
          _buildLocalHeader(context),
          Expanded(
            child: StreamBuilder<List<Person>>(
              stream: _controller.getMembers(team.id),
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return const Center(child: CircularProgressIndicator());
                }

                final members = snapshot.data ?? [];
                final coaches = members.where((m) => m.type == 'Treinador').toList();
                final players = members.where((m) => m.type == 'Jogador').toList();

                return SingleChildScrollView(
                  padding: const EdgeInsets.all(16.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _buildLocalSummaryCard(members.length),
                      const SizedBox(height: 30),
                      if (coaches.isNotEmpty) ...[
                        _buildSectionTitle("Treinadores"),
                        ...coaches.map((c) => _buildPersonCard(context, c, isCoach: true)),
                        const SizedBox(height: 30),
                      ],
                      _buildSectionTitle("Jogadores"),
                      if (players.isEmpty)
                        const Padding(
                          padding: EdgeInsets.only(top: 20),
                          child: Text("Nenhum jogador adicionado.", style: TextStyle(color: Colors.grey)),
                        )
                      else
                        ...players.map((p) => _buildPersonCard(context, p, isCoach: false)),
                      const SizedBox(height: 80),
                    ],
                  ),
                );
              },
            ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => _controller.showAddPersonDialog(context, team.id),
        backgroundColor: const Color(0xFF00C853),
        child: const Icon(Icons.add, color: Colors.white),
      ),
    );
  }

  // --- WIDGETS QUE ESTAVAM EM STATS_WIDGETS ---

  Widget _buildLocalHeader(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),
          CircleAvatar(
            backgroundColor: Colors.white24,
            child: Text(team.imageUrl.isNotEmpty && !team.imageUrl.startsWith('http') ? team.imageUrl : "🏀"),
          ),
          const SizedBox(width: 15),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(team.name, style: const TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold)),
              Text(team.season, style: const TextStyle(color: Colors.white70, fontSize: 14)),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildLocalSummaryCard(int total) {
    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)),
          ],
        ),
      ),
    );
  }

  Widget _buildPersonCard(BuildContext context, Person person, {required bool isCoach}) {
    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, style: const TextStyle(color: Colors.blue, fontWeight: FontWeight.bold, fontSize: 16)),
            ),
        title: Text(person.name, style: const TextStyle(fontWeight: FontWeight.bold)),
        trailing: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            IconButton(
              icon: const Icon(Icons.edit_outlined, color: Colors.blue),
              onPressed: () => _controller.showEditPersonDialog(context, team.id, person),
            ),
            IconButton(
              icon: const Icon(Icons.delete_outline, color: Colors.red),
              onPressed: () => _confirmDelete(context, person),
            ),
          ],
        ),
      ),
    );
  }

  void _confirmDelete(BuildContext context, Person person) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text("Eliminar?"),
        content: Text("Remover ${person.name}?"),
        actions: [
          TextButton(onPressed: () => Navigator.pop(context), child: const Text("Cancelar")),
          TextButton(
            onPressed: () {
              _controller.deletePerson(team.id, person.id);
              Navigator.pop(context);
            },
            child: const Text("Eliminar", style: TextStyle(color: Colors.red)),
          ),
        ],
      ),
    );
  }

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

// --- CONTROLLER LOCAL (SEM SUPABASE) ---

class StatsController {
  final _streamController = StreamController<List<Person>>.broadcast();

  Stream<List<Person>> getMembers(String teamId) {
    _emitMembers(teamId);
    return _streamController.stream;
  }

  void _emitMembers(String teamId) {
    final list = TeamController.members
        .where((m) => m['team_id'] == teamId)
        .map((json) => Person.fromMap(json))
        .toList();
    _streamController.add(list);
  }

  void deletePerson(String teamId, String personId) {
    TeamController.members.removeWhere((m) => m['id'] == personId);
    _emitMembers(teamId);
  }

  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 type = person?.type ?? 'Jogador';

    showDialog(
      context: context,
      builder: (ctx) => StatefulBuilder(
        builder: (ctx, setState) => AlertDialog(
          title: Text(isEdit ? "Editar" : "Adicionar"),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextField(controller: nameCtrl, decoration: const InputDecoration(labelText: "Nome")),
              DropdownButton<String>(
                value: type,
                isExpanded: true,
                items: ["Jogador", "Treinador"].map((e) => DropdownMenuItem(value: e, child: Text(e))).toList(),
                onChanged: (v) => setState(() => type = v!),
              ),
              if (type == "Jogador")
                TextField(controller: numCtrl, decoration: const InputDecoration(labelText: "Número"), keyboardType: TextInputType.number),
            ],
          ),
          actions: [
            TextButton(onPressed: () => Navigator.pop(ctx), child: const Text("Sair")),
            ElevatedButton(
              onPressed: () {
                if (isEdit) {
                  final idx = TeamController.members.indexWhere((m) => m['id'] == person.id);
                  TeamController.members[idx] = {'id': person.id, 'team_id': teamId, 'name': nameCtrl.text, 'type': type, 'number': numCtrl.text};
                } else {
                  TeamController.members.add({
                    'id': DateTime.now().toString(),
                    'team_id': teamId,
                    'name': nameCtrl.text,
                    'type': type,
                    'number': numCtrl.text
                  });
                }
                _emitMembers(teamId);
                Navigator.pop(ctx);
              },
              child: const Text("Guardar"),
            )
          ],
        ),
      ),
    );
  } 
  } 
