//
//  GroupStageSettingsView.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 31/03/2024.
//

import SwiftUI
import LeStorage

struct GroupStageSettingsView: View {
    @EnvironmentObject var dataStore: DataStore
    @Environment(Tournament.self) var tournament: Tournament
    @State private var generationDone: Bool = false

    var body: some View {
        List {
            
            if tournament.shouldVerifyGroupStage {
                Section {
                    RowButtonView("Valider les poules en l'état", role: .destructive) {
                        tournament.shouldVerifyGroupStage = false
                        do {
                            try dataStore.tournaments.addOrUpdate(instance: tournament)
                        } catch {
                            Logger.error(error)
                        }
                    }
                } footer: {
                    Text("Suite à un changement dans votre liste d'inscrits, veuillez vérifier l'intégrité de vos poules et valider que tout est ok.")
                }
            }
            
            #if DEBUG
            Section {
                RowButtonView("delete all group stages") {
                    tournament.deleteGroupStages()
                }
            }
            #endif
            
            if tournament.unsortedTeams().filter({ $0.groupStagePosition != nil }).isEmpty == false {
                Section {
                    menuBuildAllGroupStages
                } footer: {
                    Text("Efface et recréé les poules, les horaires et les résultats existants seront perdus")
                }
            }
            
            Section {
                menuGenerateGroupStage(.random)
            } footer: {
                Text("Redistribue les équipes par tirage au sort par chapeau")
            }
            
            Section {
                menuGenerateGroupStage(.snake)
            } footer: {
                Text("Redistribue les équipes par la méthode du serpentin")
            }

            Section {
                RowButtonView("Nommer les poules alphabétiquement", role: .destructive) {
                    let groupStages = tournament.groupStages()
                    groupStages.forEach { groupStage in
                        if let letter = Alphabet.letterForIndex(index: groupStage.index) {
                            groupStage.name = "Poule " + letter
                        }
                    }
                    do {
                        try dataStore.groupStages.addOrUpdate(contentOfs: groupStages)
                    } catch {
                        Logger.error(error)
                    }
                }
            }
            
            Section {
                RowButtonView("Supprimer les noms des poules", role: .destructive) {
                    let groupStages = tournament.groupStages()
                    groupStages.forEach { groupStage in
                        groupStage.name = nil
                    }
                    do {
                        try dataStore.groupStages.addOrUpdate(contentOfs: groupStages)
                    } catch {
                        Logger.error(error)
                    }
                }
            }

        }
        .overlay(alignment: .bottom) {
            if generationDone {
                Label("Poules mises à jour", systemImage: "checkmark.circle.fill")
                    .toastFormatted()
                    .deferredRendering(for: .seconds(2))
            }
        }
    }
    
    
    var menuBuildAllGroupStages: some View {
        RowButtonView("Refaire les poules", role: .destructive) {
            tournament.deleteGroupStages()
            tournament.buildGroupStages()
            generationDone = true
            tournament.shouldVerifyGroupStage = false
            _save()
        }
    }

    @ViewBuilder
    func menuGenerateGroupStage(_ mode: GroupStageOrderingMode) -> some View {
        RowButtonView("Poule \(mode.localizedLabel().lowercased())", role: .destructive, systemImage: mode.systemImage) {
            tournament.groupStageOrderingMode = mode
            tournament.refreshGroupStages()
            generationDone = true
            tournament.shouldVerifyGroupStage = false
            _save()
        }
    }
    
    private func _save() {
        do {
            try dataStore.tournaments.addOrUpdate(instance: tournament)
        } catch {
            Logger.error(error)
        }
    }
}

//#Preview {
//    GroupStageSettingsView()
//        .environment(Tournament.mock())
//}
