import 'package:flutter/material.dart';
import 'package:playmaker/screens/team_stats_page.dart';
import '../models/team_model.dart';
import '../controllers/team_controller.dart';
import 'dart:math' as math; // 👇 IMPORTANTE PARA O TRAVÃO DE MÃO

class TeamCard extends StatelessWidget {
  final Team team;
  final TeamController controller;
  final VoidCallback onFavoriteTap;
  final double sf; // <-- Variável de escala original

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

  @override
  Widget build(BuildContext context) {
    // 👇 O SEGREDO ESTÁ AQUI: TRAVÃO DE MÃO PARA TABLETS 👇
    // O sf pode crescer, mas NUNCA vai ser maior que 1.15!
    final double safeSf = math.min(sf, 1.15); 

    return Card(
      color: Colors.white,
      elevation: 3,
      margin: EdgeInsets.only(bottom: 12 * safeSf),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15 * safeSf)),
      child: ListTile(
        contentPadding: EdgeInsets.symmetric(horizontal: 16 * safeSf, vertical: 8 * safeSf),

        // --- 1. IMAGEM + FAVORITO ---
        leading: Stack(
          clipBehavior: Clip.none,
          children: [
            CircleAvatar(
              radius: 28 * safeSf,
              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: TextStyle(fontSize: 24 * safeSf),
                    )
                  : null,
            ),
            Positioned(
              left: -15 * safeSf,
              top: -10 * safeSf,
              child: IconButton(
                icon: Icon(
                  team.isFavorite ? Icons.star : Icons.star_border,
                  color: team.isFavorite ? Colors.amber : Colors.black.withOpacity(0.1),
                  size: 28 * safeSf,
                  shadows: [
                    Shadow(
                      color: Colors.black.withOpacity(team.isFavorite ? 0.3 : 0.1),
                      blurRadius: 4 * safeSf,
                    ),
                  ],
                ),
                onPressed: onFavoriteTap,
              ),
            ),
          ],
        ),

        // --- 2. TÍTULO ---
        title: Text(
          team.name,
          style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16 * safeSf),
          overflow: TextOverflow.ellipsis,
        ),

        // --- 3. SUBTÍTULO (Contagem + Época em TEMPO REAL) ---
        subtitle: Padding(
          padding: EdgeInsets.only(top: 6.0 * safeSf),
          child: Row(
            children: [
              Icon(Icons.groups_outlined, size: 16 * safeSf, color: Colors.grey),
              SizedBox(width: 4 * safeSf),
              
              StreamBuilder<int>(
                stream: controller.getPlayerCountStream(team.id),
                initialData: 0,
                builder: (context, snapshot) {
                  final count = snapshot.data ?? 0;
                  return Text(
                    "$count Jogs.", 
                    style: TextStyle(
                      color: count > 0 ? Colors.green[700] : Colors.orange,
                      fontWeight: FontWeight.bold,
                      fontSize: 13 * safeSf,
                    ),
                  );
                },
              ),
              
              SizedBox(width: 8 * safeSf),
              Expanded( 
                child: Text(
                  "|  ${team.season}",
                  style: TextStyle(color: Colors.grey, fontSize: 13 * safeSf),
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            ],
          ),
        ),

        // --- 4. BOTÕES (Estatísticas e Apagar) ---
        trailing: Row(
          mainAxisSize: MainAxisSize.min, 
          children: [
            IconButton(
              tooltip: 'Ver Estatísticas',
              icon: Icon(Icons.bar_chart_rounded, color: Colors.blue, size: 24 * safeSf),
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => TeamStatsPage(team: team),
                  ),
                );
              },
            ),
            IconButton(
              tooltip: 'Eliminar Equipa',
              icon: Icon(Icons.delete_outline, color: const Color(0xFFE74C3C), size: 24 * safeSf),
              onPressed: () => _confirmDelete(context, safeSf),
            ),
          ],
        ),
      ),
    );
  }

  void _confirmDelete(BuildContext context, double safeSf) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('Eliminar Equipa?', style: TextStyle(fontSize: 18 * safeSf, fontWeight: FontWeight.bold)),
        content: Text('Tens a certeza que queres eliminar "${team.name}"?', style: TextStyle(fontSize: 14 * safeSf)),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text('Cancelar', style: TextStyle(fontSize: 14 * safeSf)),
          ),
          TextButton(
            onPressed: () {
              controller.deleteTeam(team.id);
              Navigator.pop(context);
            },
            child: Text('Eliminar', style: TextStyle(color: Colors.red, fontSize: 14 * safeSf)),
          ),
        ],
      ),
    );
  }
}

// --- DIALOG DE CRIAÇÃO ---
class CreateTeamDialog extends StatefulWidget {
  final Function(String name, String season, String imageUrl) onConfirm;
  final double sf; 

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

  @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) {
    // 👇 MESMO TRAVÃO NO POPUP PARA NÃO FICAR GIGANTE 👇
    final double safeSf = math.min(widget.sf, 1.15); 

    return AlertDialog(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15 * safeSf)),
      title: Text('Nova Equipa', style: TextStyle(fontSize: 18 * safeSf, fontWeight: FontWeight.bold)),
      content: SingleChildScrollView(
        child: Container(
          // 👇 Limita a largura máxima no tablet para o popup não ficar super esticado!
          constraints: BoxConstraints(maxWidth: 450 * safeSf), 
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextField(
                controller: _nameController,
                style: TextStyle(fontSize: 14 * safeSf),
                decoration: InputDecoration(
                  labelText: 'Nome da Equipa', 
                  labelStyle: TextStyle(fontSize: 14 * safeSf)
                ),
                textCapitalization: TextCapitalization.words,
              ),
              SizedBox(height: 15 * safeSf),
              DropdownButtonFormField<String>(
                value: _selectedSeason,
                decoration: InputDecoration(
                  labelText: 'Temporada',
                  labelStyle: TextStyle(fontSize: 14 * safeSf)
                ),
                style: TextStyle(fontSize: 14 * safeSf, color: Colors.black87),
                items: ['2023/24', '2024/25', '2025/26']
                    .map((s) => DropdownMenuItem(value: s, child: Text(s)))
                    .toList(),
                onChanged: (val) => setState(() => _selectedSeason = val!),
              ),
              SizedBox(height: 15 * safeSf),
              TextField(
                controller: _imageController,
                style: TextStyle(fontSize: 14 * safeSf),
                decoration: InputDecoration(
                  labelText: 'URL Imagem ou Emoji',
                  labelStyle: TextStyle(fontSize: 14 * safeSf),
                  hintText: 'Ex: 🏀 ou https://...',
                  hintStyle: TextStyle(fontSize: 14 * safeSf)
                ),
              ),
            ],
          ),
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context), 
          child: Text('Cancelar', style: TextStyle(fontSize: 14 * safeSf))
        ),
        ElevatedButton(
          style: ElevatedButton.styleFrom(
            backgroundColor: const Color(0xFFE74C3C),
            padding: EdgeInsets.symmetric(horizontal: 16 * safeSf, vertical: 10 * safeSf)
          ),
          onPressed: () {
            if (_nameController.text.trim().isNotEmpty) {
              widget.onConfirm(
                _nameController.text.trim(),
                _selectedSeason,
                _imageController.text.trim(),
              );
              Navigator.pop(context);
            }
          },
          child: Text('Criar', style: TextStyle(color: Colors.white, fontSize: 14 * safeSf)),
        ),
      ],
    );
  }
}