//
//  PlayerBlockView.swift
//  Padel Tournament
//
//  Created by Razmig Sarkissian on 25/11/2023.
//

import SwiftUI

struct PlayerBlockView: View {
    @Environment(\.matchViewStyle) private var matchViewStyle
    @State var match: Match
    let teamPosition: TeamPosition
    let team: TeamRegistration?
    let teamScore: TeamScore?
    let isWalkOut: Bool
    
    var displayRestingTime: Bool {
        matchViewStyle.displayRestingTime()
    }
    
    var width: CGFloat {
        matchViewStyle == .plainStyle ? 1 : 2
    }
    
    init(match: Match, teamPosition: TeamPosition) {
        self.match = match
        self.teamPosition = teamPosition
        let theTeam = match.team(teamPosition)
        self.team = theTeam
        let theTeamScore = match.teamScore(ofTeam: theTeam)
        self.teamScore = theTeamScore
        self.isWalkOut = theTeamScore?.isWalkOut() == true
    }
    
    var names: [String]? {
        match.teamNames(team)
    }
    
    var hasWon: Bool {
        match.teamWon(team)
    }
    
    var hideScore: Bool {
        match.hasWalkoutTeam()
    }

    var scores: [String] {
        teamScore?.score?.components(separatedBy: ",") ?? []
    }

    private func _defaultLabel() -> [String] {
        var defaultLabels = [String]()
        if let previous = match.previousMatch(teamPosition) {
            defaultLabels.append("Gagnant \(previous.roundAndMatchTitle(.short))")
            if previous.isReady() == true {
                if let courtName = previous.courtName(), previous.isRunning() {
                    defaultLabels.append(courtName + "\(previous.runningDuration())")
                }
            }
        } else if let loser = match.loserMatch(teamPosition) {
            defaultLabels.append("Perdant \(loser.roundAndMatchTitle(.short))")
            if loser.isReady() == true {
                if let courtName = loser.courtName(), loser.isRunning() {
                    defaultLabels.append(courtName + "\(loser.runningDuration())")
                }
            }
        } else {
            defaultLabels.append(teamPosition.localizedLabel())
        }
        return defaultLabels
    }
    
    var body: some View {
        HStack {
            VStack(alignment: .leading) {
                ZStack(alignment: .leading) {
                    VStack {
                        if let teamName = team?.name {
                            Text(teamName).foregroundStyle(.secondary).font(.footnote)
                        }
                        Text("longLabelPlayerOne").lineLimit(1)
                        Text("longLabelPlayerTwo").lineLimit(1)
                    }
                    .opacity(0)

                    if let team {
                        if let teamScore, teamScore.luckyLoser != nil, match.isLoserBracket == false {
                            Text("Repêchée").italic().font(.caption)
                        }

                        if let teamName = team.name {
                            Text(teamName).foregroundStyle(.secondary).font(.footnote)
                        } else if team.players().isEmpty {
                            if team.isWildCard() {
                                Text("Place réservée wildcard")
                            } else {
                                Text("Place réservée")
                            }
                        }
                        VStack(alignment: .leading) {
                            ForEach(team.players()) { player in
                                Text(player.playerLabel()).lineLimit(1)
                                    .italic(player.isHere() == false)
                                    .foregroundStyle(player.isHere() == false ? .secondary : .primary)
                            }
                        }
                    } else {
                        VStack(alignment: .leading) {
                            ForEach(_defaultLabel(), id: \.self) { name in
                                Text(name)
                                    .foregroundStyle(.secondary)
                                    .lineLimit(1)
                            }
                        }
                    }
                }

                if displayRestingTime, let team {
                    TeamRowView.TeamRestingView(team: team)
                }
            }
            .bold(hasWon)
            Spacer()
            if hasWon {
                Image(systemName: "trophy")
            } else if isWalkOut {
                Text("WO")
            }
            
            if hideScore == false && scores.isEmpty == false {
                ForEach(scores.indices, id: \.self) { index in
                    if let string = scores[safe: index], string.isEmpty == false {
                        if width == 1 {
                            Divider()
                        } else {
                            Divider().frame(width: width).overlay(Color(white: 0.9))
                        }
                        
                        let parts = string.components(separatedBy: "-")
                        if parts.count == 2, let mainScore = parts.first, let supScore = parts.last {
                            HStack(spacing: 0) {
                                Text(mainScore)
                                    .font(.title3)
                                    .frame(maxWidth: 20)
                                    .scaledToFill()
                                    .minimumScaleFactor(0.5)
                                    .lineLimit(1)
                                Text(supScore)
                                    .font(.caption2)
                                    .baselineOffset(10)
                            }
                        } else {
                            Text(string)
                                .font(.title3)
                                .frame(maxWidth: 20)
                                .scaledToFill()
                                .minimumScaleFactor(0.5)
                                .lineLimit(1)
                        }
                    }
                }
            } else if let team, hasWon == false, isWalkOut == false {
                TeamWeightView(team: team, teamPosition: teamPosition)
            }
        }
    }
}
