//
//  MatchTeamDetailView.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 18/04/2024.
//

import SwiftUI

struct MatchTeamDetailView: View {
    @EnvironmentObject var tournamentStore: TournamentStore
    let match: Match
    
    var body: some View {
        NavigationStack {
            let tournament = match.currentTournament()
            List {
                if let teamOne = match.team(.one) {
                    _teamDetailView(teamOne, inTournament: tournament)
                }
                if let teamTwo = match.team(.two) {
                    _teamDetailView(teamTwo, inTournament: tournament)
                }
            }
            .headerProminence(.increased)
            .tint(.master)
        }
    }
    
    @ViewBuilder
    private func _teamDetailView(_ team: TeamRegistration, inTournament tournament: Tournament?) -> some View {
        Section {
            if let teamName = team.name, teamName.isEmpty == false {
                Text(teamName).foregroundStyle(.secondary).font(.footnote)
            }
            ForEach(team.players()) { player in
                EditablePlayerView(player: player, editingOptions: _editingOptions())
            }
            if let coachList = team.comment, coachList.isEmpty == false {
                Text("Coachs : " + coachList).foregroundStyle(.secondary).font(.footnote)
            }
        } header: {
            TeamHeaderView(team: team, teamIndex: tournament?.indexOf(team: team), tournament: tournament)
        } footer: {
            if let tournament {
                NavigationLink {
                    EditingTeamView(team: team)
                        .environment(tournament)
                } label: {
                    Text("détails de l'équipe")
                        .underline()
                }
            }
        }
    }

    private func _isFree() -> Bool {
        let tournament = match.currentTournament()
        return tournament?.isFree() == true
    }
    
    private func _editingOptions() -> [EditablePlayerView.PlayerEditingOption] {
        if _isFree() {
            return [.licenceId, .name, .presence]
        } else {
            return [.licenceId, .name, .payment]
        }
    }
    
}

//#Preview {
//    MatchTeamDetailView(match: Match.mock())
//}
