import 'package:flutter/material.dart';
import '../models/team_model.dart';
import '../controllers/team_controller.dart';
import '../screens/team_stats_page.dart'; 
class TeamCard extends StatelessWidget {
  final Team team;
  final TeamController controller;
  final VoidCallback onFavoriteTap;

  const TeamCard({
    super.key,
    required this.team,
    required this.controller,
    required this.onFavoriteTap,
  });

  @override
  Widget build(BuildContext context) {
    return Card(
      color: Colors.white, 
      elevation: 3,
      margin: const EdgeInsets.only(bottom: 12),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)),
      child: ListTile(
        contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),

   leading: Stack(
          clipBehavior: Clip.none, // Permite que a estrela flutue ligeiramente fora do círculo
          children: [
            // 1. IMAGEM DA EQUIPA
            CircleAvatar(
              radius: 28,
              backgroundColor: Colors.grey[200],
              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: 24),
                    ) 
                  : null,
            ),
            
            // 2. BOTÃO DA ESTRELA (Favorito)
            Positioned(
              left: -15, // Posiciona à esquerda da imagem
              top: -10,
              child: IconButton(
                // O segredo está em colocar o shadow dentro do Icon:
                icon: Icon(
                  team.isFavorite ? Icons.star : Icons.star_border,
                  color: team.isFavorite ? Colors.amber : Colors.black.withOpacity(0.1), // Transparente se não favorito
                  size: 28,
                  shadows: [
                    Shadow(
                      color: Colors.black.withOpacity(team.isFavorite ? 0.3 : 0.1),
                      blurRadius: 4,
                    ),
                  ],
                ),
                onPressed: onFavoriteTap,
              ),
            ),
          ],
        ),

        // --- NOME DA EQUIPA ---
        title: Text(
          team.name,
          style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
        ),

        // --- SUBTÍTULO (CONTAGEM E TEMPORADA) ---
        subtitle: Padding(
          padding: const EdgeInsets.only(top: 6.0),
          child: Row(
            children: [
              const Icon(Icons.groups_outlined, size: 16, color: Colors.grey),
              const SizedBox(width: 4),
              FutureBuilder<int>(
                future: controller.getPlayerCount(team.id),
                initialData: 0,
                builder: (context, snapshot) {
                  final count = snapshot.data ?? 0;
                  return Text(
                    "$count Jogadores",
                    style: TextStyle(
                      color: count > 0 ? Colors.green[700] : Colors.orange,
                      fontWeight: FontWeight.bold,
                      fontSize: 13,
                    ),
                  );
                },
              ),
              const SizedBox(width: 10),
              Text(
                "|  ${team.season}",
                style: const TextStyle(color: Colors.grey, fontSize: 13),
              ),
            ],
          ),
        ),

        // --- BOTÕES DE ACÇÃO À DIREITA ---
        trailing: SizedBox(
          width: 80, 
          child: Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              IconButton(
                tooltip: 'Ver Estatísticas',
                icon: const Icon(Icons.bar_chart_rounded, color: Colors.blue),
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => TeamStatsPage(team: team),
                    ),
                  );
                },
              ),
              IconButton(
                tooltip: 'Eliminar Equipa',
                icon: const Icon(Icons.delete_outline, color: Color(0xFFE74C3C)),
                onPressed: () => _confirmDelete(context),
              ),
            ],
          ),
        ),
      ),
    );
  }
  void _confirmDelete(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Eliminar Equipa?'),
        content: Text('Tens a certeza que queres eliminar "${team.name}"?'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context), 
            child: const Text('Cancelar')
          ),
          TextButton(
            onPressed: () {
              controller.deleteTeam(team.id); 
              Navigator.pop(context);
            },
            child: const Text('Eliminar', style: TextStyle(color: Colors.red))
),
        ],
      ),
    );
  }
}

class CreateTeamDialog extends StatefulWidget {
  final Function(String name, String season, String imageUrl) onConfirm;

  const CreateTeamDialog({super.key, required this.onConfirm});

  @override
  State<CreateTeamDialog> createState() => _CreateTeamDialogState();
}

class _CreateTeamDialogState extends State<CreateTeamDialog> {
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _imageController = TextEditingController();
  String _selectedSeason = '2024/25';

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text('Nova Equipa'),
      content: SingleChildScrollView(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              controller: _nameController,
              decoration: const InputDecoration(labelText: 'Nome da Equipa'),
              textCapitalization: TextCapitalization.words,
            ),
            const SizedBox(height: 15),
            DropdownButtonFormField<String>(
              value: _selectedSeason,
              decoration: const InputDecoration(labelText: 'Temporada'),
              items: ['2023/24', '2024/25', '2025/26']
                  .map((s) => DropdownMenuItem(value: s, child: Text(s)))
                  .toList(),
              onChanged: (val) => setState(() => _selectedSeason = val!),
            ),
            const SizedBox(height: 15),
            TextField(
              controller: _imageController,
              decoration: const InputDecoration(
                labelText: 'URL Imagem ou Emoji',
                hintText: 'Ex: 🏀 ou https://...',
              ),
            ),
          ],
        ),
      ),
      actions: [
        TextButton(onPressed: () => Navigator.pop(context), child: const Text('Cancelar')),
        ElevatedButton(
          style: ElevatedButton.styleFrom(backgroundColor: const Color(0xFFE74C3C)),
onPressed: () {
  if (_nameController.text.trim().isNotEmpty) {
    widget.onConfirm(
      _nameController.text.trim(), 
      _selectedSeason, 
      _imageController.text.trim()  
    );
    Navigator.pop(context);
  }
},
          child: const Text('Criar', style: TextStyle(color: Colors.white)),
        ),
      ],
    );
  }
}