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

import SwiftUI
import LeStorage

struct MatchSetupView: View {
    @EnvironmentObject var dataStore: DataStore
    var match: Match
    @State private var seedGroup: SeedInterval?

    @ViewBuilder
    var body: some View {
        ForEach(TeamPosition.allCases) { teamPosition in
            _teamView(inTeamPosition: teamPosition)
        }
    }
    
    @ViewBuilder
    func _teamView(inTeamPosition teamPosition: TeamPosition) -> some View {
        let scores = match.teamScores
        let team = scores.isEmpty ? nil : match.team(teamPosition)
        let teamScore = (team != nil) ? scores.first(where: { $0.teamRegistration == team!.id }) : nil
        let walkOutSpot = teamScore?.walkOut == 1

        if let team, teamScore?.walkOut == nil {
            VStack(alignment: .leading, spacing: 0) {
                if let teamScore, teamScore.luckyLoser != nil {
                    Text("Repêchée").italic().font(.caption)
                }
                TeamRowView(team: team, teamPosition: teamPosition)
                    .swipeActions(edge: .trailing, allowsFullSwipe: false) {
                        Button(role: .cancel) {
                            //todo
                            if match.isSeededBy(team: team, inTeamPosition: teamPosition) {
                                team.bracketPosition = nil
                                match.updateTeamScores()
                                match.enableMatch()
                                do {
                                    try dataStore.matches.addOrUpdate(instance: match)
                                } catch {
                                    Logger.error(error)
                                }
                                do {
                                    try dataStore.teamRegistrations.addOrUpdate(instance: team)
                                } catch {
                                    Logger.error(error)
                                }
                            } else {
                                match.teamWillBeWalkOut(team)
                                do {
                                    try dataStore.matches.addOrUpdate(instance: match)
                                } catch {
                                    Logger.error(error)
                                }                                
                            }
                        } label: {
                            Label("retirer", systemImage: "xmark")
                        }
                    }
            }
        } else {
            VStack(alignment: .leading) {
                if let team {
                    TeamRowView(team: team, teamPosition: teamPosition)
                        .strikethrough()
                }
                HStack {
                    let luckyLosers = walkOutSpot ? match.luckyLosers() : []
                    TeamPickerView(groupStagePosition: nil, luckyLosers: luckyLosers, teamPicked: { team in
                        print(team.pasteData())
                        if walkOutSpot {
                            match.setLuckyLoser(team: team, teamPosition: teamPosition)
                            do {
                                try dataStore.matches.addOrUpdate(instance: match)
                            } catch {
                                Logger.error(error)
                            }
                        } else {
                            team.setSeedPosition(inSpot: match, slot: teamPosition, opposingSeeding: false)
                            do {
                                try dataStore.matches.addOrUpdate(instance: match)
                            } catch {
                                Logger.error(error)
                            }
                            do {
                                try dataStore.teamRegistrations.addOrUpdate(instance: team)
                            } catch {
                                Logger.error(error)
                            }
                        }
                    })
                    if let tournament = match.currentTournament() {
                        let availableSeedGroups = tournament.availableSeedGroups()
                        Text("ou")
                        Menu {
                            if walkOutSpot, luckyLosers.isEmpty == false {
                                Button {
                                    if let randomTeam = luckyLosers.randomElement() {
                                        match.setLuckyLoser(team: randomTeam, teamPosition: teamPosition)
                                        do {
                                            try dataStore.matches.addOrUpdate(instance: match)
                                        } catch {
                                            Logger.error(error)
                                        }
                                    }
                                } label: {
                                    Label("Repêchage", systemImage: "dice")
                                }
                            }
                            ForEach(availableSeedGroups, id: \.self) { seedGroup in
                                Button {
                                    if let randomTeam = tournament.randomSeed(fromSeedGroup: seedGroup) {
                                        randomTeam.setSeedPosition(inSpot: match, slot: teamPosition, opposingSeeding: false)
                                        do {
                                            try dataStore.matches.addOrUpdate(instance: match)
                                        } catch {
                                            Logger.error(error)
                                        }
                                        do {
                                            try dataStore.teamRegistrations.addOrUpdate(instance: randomTeam)
                                        } catch {
                                            Logger.error(error)
                                        }
                                    }
                                } label: {
                                    Label(seedGroup.localizedLabel(), systemImage: "dice")
                                }
                            }
                        } label: {
                            Text("Tirer au sort").tag(nil as SeedInterval?)
                                .underline()
                        }
                        .disabled(availableSeedGroups.isEmpty && walkOutSpot == false)
                        Spacer()
                        if match.isSeedLocked(atTeamPosition: teamPosition) {
                            Button {
                                match.unlockSeedPosition(atTeamPosition: teamPosition)
                                do {
                                    try dataStore.matches.addOrUpdate(instance: match)
                                } catch {
                                    Logger.error(error)
                                }
                            } label: {
                                Text("Libérer")
                                    .underline()
                            }
                        } else {
                            Button {
                                _ = match.lockAndGetSeedPosition(atTeamPosition: teamPosition)
                                do {
                                    try dataStore.matches.addOrUpdate(instance: match)
                                } catch {
                                    Logger.error(error)
                                }
                            } label: {
                                Text("Réserver")
                                    .underline()
                            }
                        }
                    }
                }
                .fixedSize(horizontal: false, vertical: true)
                .buttonStyle(.borderless)
            }
        }
    }
}

//#Preview {
//    MatchSetupView(match: Match.mock())
//        .environmentObject(DataStore.shared)
//}
