import 'package:flutter/material.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 (ESTILO DIALOG CENTRAL) ---
  void _showFilterDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setModalState) {
            return AlertDialog(
              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(
                  color: isSelected ? const Color(0xFFE74C3C) : Colors.black,
                  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.hasData) return const Center(child: CircularProgressIndicator());
        
        var data = snapshot.data!;

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

        // 3. Ordenação (O controller já lida com favoritos, aqui aplicamos a manual)
        if (_currentSort == 'Recentes') {
          data.sort((a, b) => b['id'].compareTo(a['id']));
        } else if (_currentSort == 'Nome') {
          data.sort((a, b) => a['name'].toString().compareTo(b['name'].toString()));
        } else if (_currentSort == 'Tamanho') {
          data.sort((a, b) {
            int countA = TeamController.members.where((m) => m['team_id'] == a['id']).length;
            int countB = TeamController.members.where((m) => m['team_id'] == b['id']).length;
            return countB.compareTo(countA);
          });
        }

        if (data.isEmpty) {
          return const Center(child: Text("Nenhuma equipa encontrada."));
        }

        return ListView.builder(
          padding: const EdgeInsets.symmetric(horizontal: 16),
          itemCount: data.length,
          itemBuilder: (context, index) {
            final team = Team.fromMap(data[index]);
            return TeamCard(
              team: team, 
              controller: controller,
              onFavoriteTap: () => controller.toggleFavorite(team.id),
            );
          },
        );
      },
    );
  }

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