//
//  GroupStagesView.swift
//  Padel Tournament
//
//  Created by Razmig Sarkissian on 11/12/2023.
//

import SwiftUI
import LeStorage

struct GroupStagesView: View {
    var tournament: Tournament
    @State private var selectedDestination: GroupStageDestination?
    
    enum GroupStageDestination: Selectable, Identifiable, Equatable {
        static func == (lhs: GroupStagesView.GroupStageDestination, rhs: GroupStagesView.GroupStageDestination) -> Bool {
            lhs.id == rhs.id
        }
        
        case all(Tournament)
        case groupStage(GroupStage)
        
        var id: String {
            switch self {
            case .all:
                return "all-group-stage"
            case .groupStage(let groupStage):
                return groupStage.id
            }
        }
        
        func selectionLabel(index: Int) -> String {
            switch self {
            case .all:
                return "Tout"
            case .groupStage(let groupStage):
                return groupStage.groupStageTitle()
            }
        }
        
        func badgeValue() -> Int? {
            switch self {
            case .all:
                return nil
            case .groupStage(let groupStage):
                return groupStage.badgeValue()
            }
        }
        
        func badgeValueColor() -> Color? {
            return nil
        }
        
        func badgeImage() -> Badge? {
            switch self {
            case .all(let tournament):
                if tournament.groupStageAdditionalQualified > 0 && tournament.moreQualifiedToDraw() > 0 && tournament.missingQualifiedFromGroupStages().isEmpty == false {
                    return .custom(systemName: "exclamationmark.circle.fill", color: .logoBackground)
                } else {
                    return nil
                }
            case .groupStage(let groupStage):
                return groupStage.badgeImage()
            }
        }
    }
    
    var allMatches: [Match] {
        tournament.groupStagesMatches()
    }
    
    init(tournament: Tournament) {
        self.tournament = tournament

        if tournament.shouldVerifyGroupStage {
            _selectedDestination = State(wrappedValue: nil)
        } else if tournament.unsortedTeams().filter({ $0.groupStagePosition != nil }).isEmpty {
            _selectedDestination = State(wrappedValue: nil)
        } else {
            let gs = tournament.getActiveGroupStage()
            if let gs {
                _selectedDestination = State(wrappedValue: .groupStage(gs))
            }
        }
    }
    
    func allDestinations() -> [GroupStageDestination] {
        var allDestinations : [GroupStageDestination] = [.all(tournament)]
        let groupStageDestinations : [GroupStageDestination] = tournament.groupStages().map { GroupStageDestination.groupStage($0) }
        allDestinations.append(contentsOf: groupStageDestinations)
        return allDestinations
    }

    var body: some View {
        VStack(spacing: 0) {
            GenericDestinationPickerView(selectedDestination: $selectedDestination, destinations: allDestinations(), nilDestinationIsValid: true)
            switch selectedDestination {
            case .all:
                let finishedMatches = tournament.finishedMatches(allMatches)

                List {
                    if tournament.groupStageAdditionalQualified > 0 {
                        let missingQualifiedFromGroupStages = tournament.missingQualifiedFromGroupStages()
                        Section {
                            let name = "\((tournament.qualifiedPerGroupStage + 1).ordinalFormatted())"
                            
                            NavigationLink {
                                SpinDrawView(drawees: ["Qualification d'un \(name) de poule"], segments: missingQualifiedFromGroupStages) { results in
                                    results.forEach { drawResult in
                                        missingQualifiedFromGroupStages[drawResult.drawIndex].qualified = true
                                        do {
                                            try self.tournament.tournamentStore.teamRegistrations.addOrUpdate(instance: missingQualifiedFromGroupStages[drawResult.drawIndex])
                                        } catch {
                                            Logger.error(error)
                                        }
                                    }
                                }
                            } label: {
                                Label {
                                    Text("Qualifier un \(name) de poule par tirage au sort")
                                } icon: {
                                    Image(systemName: "exclamationmark.circle.fill")
                                        .foregroundStyle(.logoBackground)
                                }
                            }
                            .disabled(tournament.moreQualifiedToDraw() == 0 || missingQualifiedFromGroupStages.isEmpty)
                        } footer: {
                            if tournament.moreQualifiedToDraw() == 0 {
                                Text("Aucune équipe supplémentaire à qualifier. Vous pouvez en rajouter en modifier le paramètre dans structure.")
                            } else if missingQualifiedFromGroupStages.isEmpty {
                                Text("Aucune équipe supplémentaire à tirer au sort. Attendez la fin des poules.")
                            }
                        }
                    }

                    let runningMatches = tournament.runningMatches(allMatches)
                    MatchListView(section: "en cours", matches: runningMatches, matchViewStyle: .standardStyle, isExpanded: false)
                    MatchListView(section: "prêt à démarrer", matches: tournament.availableToStart(allMatches, in: runningMatches), matchViewStyle: .standardStyle, isExpanded: false)
                    MatchListView(section: "à lancer", matches: tournament.readyMatches(allMatches), matchViewStyle: .standardStyle, isExpanded: false)
                    MatchListView(section: "terminés", matches: finishedMatches, matchViewStyle: .standardStyle, isExpanded: false)
                }
                .navigationTitle("Toutes les poules")
            case .groupStage(let groupStage):
                GroupStageView(groupStage: groupStage).id(groupStage.id)
            case nil:
                GroupStagesSettingsView()
                    .navigationTitle("Réglages")
            }
        }
        .navigationBarTitleDisplayMode(.inline)
        .toolbarBackground(.visible, for: .navigationBar)
    }
}
