//
//  TeamPickerView.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 23/03/2024.
//

import SwiftUI

struct TeamPickerView: View {
    @EnvironmentObject var dataStore: DataStore
    @Environment(Tournament.self) var tournament: Tournament
    @Environment(\.dismiss) private var dismiss
    @State private var confirmTeam: TeamRegistration?
    @State private var presentTeamPickerView: Bool = false
    @State private var searchField: String = ""
    @State private var sortOrder: SortOrder = .ascending
    
    var shouldConfirm: Bool = false
    var groupStagePosition: Int? = nil
    var round: Round? = nil
    var matchTypeContext: MatchType = .bracket
    var luckyLosers: [TeamRegistration] = []
    let teamPicked: ((TeamRegistration) -> (Void))
    
    var confirmationRequest: Binding<Bool> {
        Binding {
            confirmTeam != nil
        } set: { _ in
        }
    }
    
    var body: some View {
        ConfirmButtonView(shouldConfirm: shouldConfirm, message: MatchSetupView.confirmationMessage) {
            presentTeamPickerView = true
        } label: {
            Text("Choisir")
                .underline()
        }
        .sheet(isPresented: $presentTeamPickerView) {
            NavigationStack {
                List {
                    if matchTypeContext == .loserBracket, let losers = round?.parentRound?.losers() {
                        _sectionView(losers.sorted(by: \.weight, order: sortOrder), title: "Perdant du tour précédent")
                    }

                    if matchTypeContext == .loserBracket, let losers = round?.previousRound()?.winners() {
                        _sectionView(losers.sorted(by: \.weight, order: sortOrder), title: "Gagnant du tour précédent")
                    }

                    if let groupStagePosition, let replacementRangeExtended = tournament.replacementRangeExtended(groupStagePosition: groupStagePosition) {
                        Section {
                            GroupStageTeamReplacementView.TeamRangeView(teamRange: replacementRangeExtended, playerWeight: 0)
                        } header: {
                            Text("Même ligne en poule")
                        }
                    }
                    _sectionView(luckyLosers.sorted(by: \.weight, order: sortOrder), title: "Repêchage")
                    
                    let qualified = tournament.availableQualifiedTeams()
                    _sectionView(qualified.sorted(by: \.weight, order: sortOrder), title: "Qualifiées entrants")

                    
                    let teams = tournament.selectedSortedTeams()
                    if matchTypeContext == .loserBracket {
                        _sectionView(teams.filter({ $0.inGroupStage() && $0.qualified == false }).sorted(by: \.weight, order: sortOrder), title: "Non qualifié de poules")
                    }
                    
                    _sectionView(teams.filter({ $0.availableForSeedPick() }).sorted(by: \.weight, order: sortOrder), title: "Disponible")
                    _sectionView(teams.filter({ $0.inGroupStage() }).sorted(by: \.weight, order: sortOrder), title: "Déjà placée en poule")
                    _sectionView(teams.filter({ $0.inRound() }).sorted(by: \.weight, order: sortOrder), title: "Déjà placée dans le tableau")
                }
                .searchable(text: $searchField, placement: .navigationBarDrawer(displayMode: .always))
                .keyboardType(.alphabet)
                .autocorrectionDisabled()
                .navigationTitle("Choisir une équipe")
                .toolbarBackground(.visible, for: .navigationBar)
                .navigationBarTitleDisplayMode(.inline)
                .toolbar {
                    ToolbarItem(placement: .topBarLeading) {
                        Button("Annuler", role: .cancel) {
                            presentTeamPickerView = false
                        }
                    }
                    ToolbarItem(placement: .topBarTrailing) {
                        Menu {
                            Section {
                                Picker(selection: $sortOrder) {
                                    Label("Trier les équipes par poids croissant", systemImage: "chevron.up").tag(SortOrder.ascending)
                                        .labelStyle(.titleAndIcon)
                                    Label("Trier les équipes par poids décroissant", systemImage: "chevron.down").tag(SortOrder.descending)
                                        .labelStyle(.titleAndIcon)
                                } label: {
                                    Text("Trier les équipes par poids")
                                }
                                .pickerStyle(.inline)
                            } header: {
                                Text("Trier les équipes par poids")
                            }
                        } label: {
                            HStack {
                                Text("Poids")
                                Image(systemName: sortOrder == .ascending ? "chevron.up" : "chevron.down")
                            }
                        }
                    }
                }
            }
            .tint(.master)
        }
    }
    
    @ViewBuilder
    private func _sectionView(_ teams: [TeamRegistration], title: String) -> some View {
        if teams.isEmpty == false {
            Section {
                _teamListView(teams)
            } header: {
                Text(title)
            }
        }
    }

    @ViewBuilder
    private func _teamListView(_ teams: [TeamRegistration]) -> some View {
        let selectedSortedTeams = tournament.selectedSortedTeams()
        ForEach(teams) { team in
            if searchField.isEmpty || team.contains(searchField) {
                Button {
                    teamPicked(team)
                    presentTeamPickerView = false
//                    if team.inRound() {
//                        confirmTeam = team
//                    } else {
//                        teamPicked(team)
//                        presentTeamPickerView = false
//                    }
                } label: {
                    let teamIndex = team.index(in: selectedSortedTeams)
                    TeamRowView(team: team, teamIndex: teamIndex)
                        .environment(\.isEditingTournamentSeed, .constant(false))
                        .contentShape(Rectangle())
                }
                .frame(maxWidth: .infinity)
                .buttonStyle(.plain)
                .id(team.id)
                .listRowView(isActive: matchTypeContext == .loserBracket && round?.teams().map({ $0.id }).contains(team.id) == true, color: .green, hideColorVariation: true)
//                .confirmationDialog("Attention", isPresented: confirmationRequest, titleVisibility: .visible) {
//                    Button("Retirer du tableau", role: .destructive) {
//                        teamPicked(confirmTeam!)
//                        presentTeamPickerView = false
//                    }
//                    
//                    Button("Annuler", role: .cancel) {
//                        confirmTeam = nil
//                    }
//                } message: {
//                    Text("Vous êtes sur le point de retirer cette équipe du tableau pour le replacer, cela effacera les résultats des matchs déjà joués par cette équipe dans le tableau.")
//                }
            }
        }
    }
}

//#Preview {
//    TeamPickerView(teamPicked: { team in
//    })
//    .environment(Tournament.mock())
//    .environmentObject(DataStore.shared)
//
//}
