import 'package:flutter/material.dart';
import 'package:playmaker/screens/team_stats_page.dart';
import '../controllers/team_controller.dart';
import '../models/team_model.dart';
import '../widgets/team_widgets.dart';

class TeamsPage extends StatefulWidget {
  const TeamsPage({super.key});

  @override
  State<TeamsPage> createState() => _TeamsPageState();
}

class _TeamsPageState extends State<TeamsPage> {
  final TeamController controller = TeamController();
  final TextEditingController _searchController = TextEditingController();
  
  String _selectedSeason = 'Todas';
  String _currentSort = 'Recentes';
  String _searchQuery = '';

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

  // --- POPUP DE FILTROS ---
  void _showFilterDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setModalState) {
            return AlertDialog(
              backgroundColor: const Color(0xFF2C3E50), // 2. CORRIGIDO: Fundo escuro
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
              title: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  const Text(
                    "Filtros de pesquisa",
                    style: TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold),
                  ),
                  IconButton(
                    icon: const Icon(Icons.close, color: Colors.white, size: 20),
                    onPressed: () => Navigator.pop(context),
                  )
                ],
              ),
              content: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  const Divider(color: Colors.white24),
                  const SizedBox(height: 16),
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // Coluna Temporada
                      Expanded(
                        child: _buildPopupColumn(
                          title: "TEMPORADA",
                          options: ['Todas', '2023/24', '2024/25', '2025/26'],
                          currentValue: _selectedSeason,
                          onSelect: (val) {
                            setState(() => _selectedSeason = val);
                            setModalState(() {}); 
                          },
                        ),
                      ),
                      const SizedBox(width: 20),
                      // Coluna Ordenar
                      Expanded(
                        child: _buildPopupColumn(
                          title: "ORDENAR POR",
                          options: ['Recentes', 'Nome', 'Tamanho'],
                          currentValue: _currentSort,
                          onSelect: (val) {
                            setState(() => _currentSort = val);
                            setModalState(() {});
                          },
                        ),
                      ),
                    ],
                  ),
                ],
              ),
              actions: [
                TextButton(
                  onPressed: () => Navigator.pop(context),
                  child: const Text("CONCLUÍDO", style: TextStyle(color: Color(0xFFE74C3C), fontWeight: FontWeight.bold)),
                ),
              ],
            );
          },
        );
      },
    );
  }

  Widget _buildPopupColumn({
    required String title,
    required List<String> options,
    required String currentValue,
    required Function(String) onSelect,
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(title, style: const TextStyle(color: Colors.grey, fontSize: 11, fontWeight: FontWeight.bold)),
        const SizedBox(height: 12),
        ...options.map((opt) {
          final isSelected = currentValue == opt;
          return InkWell(
            onTap: () => onSelect(opt),
            child: Padding(
              padding: const EdgeInsets.symmetric(vertical: 8.0),
              child: Text(
                opt,
                style: TextStyle(
                  // 3. CORRIGIDO: Cor do texto (Branco se não selecionado, Vermelho se selecionado)
                  color: isSelected ? const Color(0xFFE74C3C) : Colors.white70,
                  fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                ),
              ),
            ),
          );
        }).toList(),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF5F7FA),
      appBar: AppBar(
        title: const Text("Minhas Equipas", style: TextStyle(fontWeight: FontWeight.bold)),
        backgroundColor: const Color(0xFFF5F7FA),
        elevation: 0,
        actions: [
          IconButton(
            icon: const Icon(Icons.filter_list, color: Color(0xFFE74C3C)),
            onPressed: () => _showFilterDialog(context),
          ),
        ],
      ),
      body: Column(
        children: [
          _buildSearchBar(),
          Expanded(child: _buildTeamsList()),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        backgroundColor: const Color(0xFFE74C3C),
        child: const Icon(Icons.add, color: Colors.white),
        onPressed: () => _showCreateDialog(context),
      ),
    );
  }

  Widget _buildSearchBar() {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: TextField(
        controller: _searchController,
        onChanged: (v) => setState(() => _searchQuery = v.toLowerCase()),
        decoration: InputDecoration(
          hintText: 'Pesquisar equipa...',
          prefixIcon: const Icon(Icons.search, color: Color(0xFFE74C3C)),
          filled: true,
          fillColor: Colors.white,
          border: OutlineInputBorder(borderRadius: BorderRadius.circular(15), borderSide: BorderSide.none),
        ),
      ),
    );
  }

  Widget _buildTeamsList() {
    return StreamBuilder<List<Map<String, dynamic>>>(
      stream: controller.teamsStream,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Center(child: CircularProgressIndicator());
        }
        
        if (!snapshot.hasData || snapshot.data!.isEmpty) {
          return const Center(child: Text("Nenhuma equipa encontrada."));
        }

        var data = List<Map<String, dynamic>>.from(snapshot.data!);

        // --- 1. FILTROS ---
        if (_selectedSeason != 'Todas') {
          data = data.where((t) => t['season'] == _selectedSeason).toList();
        }
        if (_searchQuery.isNotEmpty) {
          data = data.where((t) => t['name'].toString().toLowerCase().contains(_searchQuery)).toList();
        }

        // --- 2. ORDENAÇÃO (FAVORITOS PRIMEIRO) ---
        data.sort((a, b) {
          // Apanhar o estado de favorito (tratando null como false)
          bool favA = a['is_favorite'] ?? false;
          bool favB = b['is_favorite'] ?? false;

          // REGRA 1: Favoritos aparecem sempre primeiro
          if (favA && !favB) return -1; // A sobe
          if (!favA && favB) return 1;  // B sobe

          // REGRA 2: Se o estado de favorito for igual, aplica o filtro do utilizador
          if (_currentSort == 'Nome') {
            return a['name'].toString().compareTo(b['name'].toString());
          } else { // Recentes
            return (b['created_at'] ?? '').toString().compareTo((a['created_at'] ?? '').toString());
          }
        });

        return ListView.builder(
          padding: const EdgeInsets.symmetric(horizontal: 16),
          itemCount: data.length,
          itemBuilder: (context, index) {
            final team = Team.fromMap(data[index]);
            
            // Navegação para estatísticas
            return GestureDetector(
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => TeamStatsPage(team: team)),
                );
              },
              child: TeamCard(
                team: team, 
                controller: controller,
                onFavoriteTap: () => controller.toggleFavorite(team.id, team.isFavorite),
              ),
            );
          },
        );
      },
    );
  }

  void _showCreateDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => CreateTeamDialog(
        onConfirm: (name, season, imageUrl) => controller.createTeam(name, season, imageUrl),
        
      ),
    );
  }
  
}