//
//  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 presentTeamPickerView: Bool = false
    @State private var searchField: String = ""
    var groupStagePosition: Int? = nil
    var luckyLosers: [TeamRegistration] = []
    let teamPicked: ((TeamRegistration) -> (Void))

    var body: some View {
        Button {
            presentTeamPickerView = true
        } label: {
            Text("Choisir")
                .underline()
        }
        .sheet(isPresented: $presentTeamPickerView) {
            NavigationStack {
                List {
                    if let groupStagePosition, let replacementRangeExtended = tournament.replacementRangeExtended(groupStagePosition: groupStagePosition) {
                        Section {
                            GroupStageTeamReplacementView.TeamRangeView(teamRange: replacementRangeExtended, playerWeight: 0)
                        } header: {
                            Text("Même ligne en poule")
                        }
                    }
                    let teams = tournament.selectedSortedTeams()
                    if luckyLosers.isEmpty == false {
                        Section {
                            _teamListView(luckyLosers.sorted(by: \.weight))
                        } header: {
                            Text("Repêchage")
                        }
                    }
                    
                    let qualified = tournament.availableQualifiedTeams()
                    if qualified.isEmpty == false {
                        Section {
                            _teamListView(qualified.sorted(by: \.weight))
                        } header: {
                            Text("Qualifiées entrants")
                        }
                    }
                    
                    Section {
                        _teamListView(teams.filter({ $0.availableForSeedPick() }).sorted(by: \.weight).reversed())
                    } header: {
                        Text("Disponible")
                    }
                    Section {
                        _teamListView(teams.filter({ $0.inGroupStage() }).sorted(by: \.groupStagePosition!).reversed())
                    } header: {
                        Text("Déjà placée en poule")
                    }
                    Section {
                        _teamListView(teams.filter({ $0.inRound() }).sorted(by: \.bracketPosition!).reversed())
                    } header: {
                        Text("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)
            }
            .tint(.master)
        }
    }
    
    private func _teamListView(_ teams: [TeamRegistration]) -> some View {
        ForEach(teams) { team in
            if searchField.isEmpty || team.contains(searchField) {
                Button {
                    teamPicked(team)
                    presentTeamPickerView = false
                } label: {
                    TeamRowView(team: team)
                        .contentShape(Rectangle())
                }
                .frame(maxWidth: .infinity)
                .buttonStyle(.plain)
            }
        }
    }
}

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