import 'package:flutter/material.dart';
import 'package:playmaker/pages/PlacarPage.dart'; // Garante que o import está correto
import '../controllers/team_controller.dart';
import '../controllers/game_controller.dart'; // Import necessário

// --- CARD DE EXIBIÇÃO DO JOGO (Mantém-se quase igual) ---
class GameResultCard extends StatelessWidget {
  final String gameId;
  final String myTeam, opponentTeam, myScore, opponentScore, status, season;

  const GameResultCard({
    super.key,
    required this.gameId,
    required this.myTeam,
    required this.opponentTeam,
    required this.myScore,
    required this.opponentScore,
    required this.status,
    required this.season,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20),
        boxShadow: const [BoxShadow(color: Colors.black12, blurRadius: 10)],
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Expanded(child: _buildTeamInfo(myTeam, const Color(0xFFE74C3C))),
          _buildScoreCenter(context, gameId),
          Expanded(child: _buildTeamInfo(opponentTeam, Colors.black87)),
        ],
      ),
    );
  }

  Widget _buildTeamInfo(String name, Color color) {
    return Column(
      children: [
        CircleAvatar(backgroundColor: color, child: const Icon(Icons.shield, color: Colors.white)),
        const SizedBox(height: 4),
        Text(name, 
          style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 12),
          textAlign: TextAlign.center,
          overflow: TextOverflow.ellipsis,
        ),
      ],
    );
  }

  Widget _buildScoreCenter(BuildContext context, String id) {
    return Column(
      children: [
        Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            _scoreBox(myScore, Colors.green),
            const Text(" : ", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20)),
            _scoreBox(opponentScore, Colors.grey),
          ],
        ),
        const SizedBox(height: 8),
        TextButton.icon(
          onPressed: () {
            // NAVEGAÇÃO PARA O PLACAR (Usando o ID real)
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => PlacarPage(
                  gameId: id,
                  myTeam: myTeam,
                  opponentTeam: opponentTeam,
                ),
              ),
            );
          },
          icon: const Icon(Icons.play_circle_fill, size: 16, color: Color(0xFFE74C3C)),
          label: const Text("RETORNAR", style: TextStyle(fontSize: 10, color: Color(0xFFE74C3C), fontWeight: FontWeight.bold)),
          style: TextButton.styleFrom(
            backgroundColor: const Color(0xFFE74C3C).withOpacity(0.1),
            padding: const EdgeInsets.symmetric(horizontal: 12),
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
            visualDensity: VisualDensity.compact,
          ),
        ),
        const SizedBox(height: 4),
        Text(status, style: const TextStyle(fontSize: 10, color: Colors.blue, fontWeight: FontWeight.bold)),
      ],
    );
  }

  Widget _scoreBox(String pts, Color c) => Container(
    padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
    decoration: BoxDecoration(color: c, borderRadius: BorderRadius.circular(8)),
    child: Text(pts, style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold)),
  );
}

// --- POPUP DE CRIAÇÃO (MODIFICADO PARA SUPABASE) ---
class CreateGameDialogManual extends StatefulWidget {
  final TeamController teamController;
  final GameController gameController; // Recebemos o controller do jogo

  const CreateGameDialogManual({
    super.key, 
    required this.teamController, 
    required this.gameController
  });

  @override
  State<CreateGameDialogManual> createState() => _CreateGameDialogManualState();
}

class _CreateGameDialogManualState extends State<CreateGameDialogManual> {
  late TextEditingController _seasonController;
  final TextEditingController _myTeamController = TextEditingController();
  final TextEditingController _opponentController = TextEditingController();
  
  bool _isLoading = false; // Para mostrar loading no botão

  @override
  void initState() {
    super.initState();
    _seasonController = TextEditingController(text: _calculateSeason());
  }

  String _calculateSeason() {
    final now = DateTime.now();
    return now.month >= 7 ? "${now.year}/${(now.year + 1).toString().substring(2)}" : "${now.year - 1}/${now.year.toString().substring(2)}";
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
      title: const Text('Configurar Partida', style: TextStyle(fontWeight: FontWeight.bold)),
      content: SingleChildScrollView(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              controller: _seasonController,
              decoration: const InputDecoration(labelText: 'Temporada', border: OutlineInputBorder(), prefixIcon: Icon(Icons.calendar_today)),
            ),
            const SizedBox(height: 15),
            
            // Usamos Autocomplete para equipas (Assumindo que TeamController já é Supabase)
            _buildSearch(label: "Minha Equipa", controller: _myTeamController),
            
            const Padding(padding: EdgeInsets.symmetric(vertical: 8), child: Text("VS", style: TextStyle(fontWeight: FontWeight.bold, color: Colors.grey))),
            
            _buildSearch(label: "Adversário", controller: _opponentController),
          ],
        ),
      ),
      actions: [
        TextButton(onPressed: () => Navigator.pop(context), child: const Text('CANCELAR')),
        
        ElevatedButton(
          style: ElevatedButton.styleFrom(
            backgroundColor: const Color(0xFFE74C3C),
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
          ),
          onPressed: _isLoading ? null : () async {
            if (_myTeamController.text.isNotEmpty && _opponentController.text.isNotEmpty) {
              setState(() => _isLoading = true);

              // 1. CRIAR NO SUPABASE E OBTER O ID REAL
              String? newGameId = await widget.gameController.createGame(
                _myTeamController.text,
                _opponentController.text,
                _seasonController.text,
              );

              setState(() => _isLoading = false);

              if (newGameId != null && context.mounted) {
                // 2. Fechar Popup
                Navigator.pop(context);

                // 3. Ir para o Placar com o ID real do banco
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => PlacarPage(
                      gameId: newGameId,
                      myTeam: _myTeamController.text,
                      opponentTeam: _opponentController.text,
                    ),
                  ),
                );
              }
            }
          },
          child: _isLoading 
            ? const SizedBox(width: 20, height: 20, child: CircularProgressIndicator(color: Colors.white, strokeWidth: 2))
            : const Text('CRIAR', style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold)),
        ),
      ],
    );
  }
  

  Widget _buildSearch({required String label, required TextEditingController controller}) {
    return StreamBuilder<List<Map<String, dynamic>>>(
      stream: widget.teamController.teamsStream,
      builder: (context, snapshot) {
        List<String> teamList = snapshot.hasData 
            ? snapshot.data!.map((t) => t['name'].toString()).toList() 
            : [];
            
        return Autocomplete<String>(
          optionsBuilder: (val) {
            if (val.text.isEmpty) return const Iterable<String>.empty();
            return teamList.where((t) => t.toLowerCase().contains(val.text.toLowerCase()));
          },
          onSelected: (String selection) {
            controller.text = selection;
          },
          fieldViewBuilder: (ctx, txtCtrl, node, submit) {
            // Sincronizar o controller interno do Autocomplete com o nosso controller externo
            if (txtCtrl.text.isEmpty && controller.text.isNotEmpty) {
               txtCtrl.text = controller.text;
            }
            // Importante: Guardar o valor escrito mesmo que não selecionado da lista
            txtCtrl.addListener(() {
               controller.text = txtCtrl.text;
            });
            
            return TextField(
              controller: txtCtrl,
              focusNode: node,
              decoration: InputDecoration(
                labelText: label, 
                prefixIcon: const Icon(Icons.search), 
                border: const OutlineInputBorder()
              ),
            );
          },
        );
      },
    );
  }
}