//
//  TournamentInscriptionView.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 19/05/2024.
//

import SwiftUI
import LeStorage

struct TournamentInscriptionView: View {
    @EnvironmentObject var dataStore: DataStore
    var tournament: Tournament

    @ViewBuilder
    var body: some View {
        NavigationLink(value: Screen.inscription) {
            LabeledContent {
                Text(tournament.unsortedTeamsWithoutWO().count.formatted() + "/" + tournament.teamCount.formatted())
            } label: {
                Text("Gestion des inscriptions")
                if let closedRegistrationDate = tournament.closedRegistrationDate {
                    Text("clôturé le " + closedRegistrationDate.formatted(date: .abbreviated, time: .shortened))
                } else if tournament.enableOnlineRegistration {
                    Text("Inscription en ligne activée")
                } else if tournament.onlineRegistrationCanBeEnabled() {
                    Text("Inscription en ligne désactivée")
                }
            }
        }
        
        if tournament.inscriptionClosed() == false && tournament.hasStarted() == false {
            TournamentDeadlinesView(tournament: tournament)
        }
    }
    
    private func _save() {
        do {
            try dataStore.tournaments.addOrUpdate(instance: tournament)
        } catch {
            Logger.error(error)
        }
    }

}

struct TournamentDeadlinesView: View {
    let tournament: Tournament
    
    var body: some View {
        ForEach(TournamentDeadlineType.allCases, id: \.self) { deadlineType in
            if let deadlineDate = tournament.deadline(for: deadlineType) {
                LabeledContent {
                    VStack(alignment: .trailing, spacing: 2) {
                        Text(deadlineDate.formatted(.dateTime.hour().minute()))
                            .foregroundStyle(.primary)
                        Text(deadlineDate.formatted(.dateTime.weekday(.abbreviated).day().month()))
                            .foregroundStyle(.secondary)
                    }
                } label: {
                    Text(deadlineType.rawValue)
                    Text("Date limite")
                }
            }
        }
    }
}
