//
//  RoundScheduleEditorView.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 07/04/2024.
//

import SwiftUI
import LeStorage

struct RoundScheduleEditorView: View {
    @EnvironmentObject var dataStore: DataStore
    
    var round: Round
    var tournament: Tournament
    @State private var startDate: Date

    init(round: Round, tournament: Tournament) {
        self.round = round
        self.tournament = tournament
        self._startDate = State(wrappedValue: round.startDate ?? round.playedMatches().first?.startDate ?? tournament.startDate)
    }
    
    var body: some View {
        @Bindable var round = round
        List {
            MatchFormatPickingView(matchFormat: $round.matchFormat) {
                await _updateSchedule()
            }
            
            DatePickingView(title: "Horaire minimum", startDate: $startDate, currentDate: $round.startDate, duration: round.matchFormat.getEstimatedDuration(tournament.additionalEstimationDuration)) {
                await _updateSchedule()
            }
            
            ForEach(round.playedMatches()) { match in
                MatchScheduleEditorView(match: match, tournament: tournament)
                    .id(UUID())
            }
        }
        .navigationBarTitleDisplayMode(.inline)
        .toolbarBackground(.visible, for: .navigationBar)
        .onChange(of: round.startDate) {
            _save()
        }
        .onChange(of: round.matchFormat) {
            let upperRounds = tournament.rounds()
            round.updateMatchFormatOfAllMatches(round.matchFormat)
            for index in (0..<round.index).reversed() {
                if let upperRound = upperRounds.filter({ $0.index == index }).first {
                    upperRound.updateMatchFormat(round.matchFormat, checkIfPossible: true, andLoserBracket: false)
                }
            }
            _save()
        }
    }
    
    private func _updateSchedule() async {
        tournament.matchScheduler()?.updateBracketSchedule(tournament: tournament, fromRoundId: round.id, fromMatchId: nil, startDate: startDate)
        round.startDate = startDate
        _save()
    }
    
    private func _save() {
        do {
            try dataStore.rounds.addOrUpdate(instance: round)
        } catch {
            Logger.error(error)
        }
    }
}

//#Preview {
//    RoundScheduleEditorView(round: Round.mock(), tournament: Tournament.mock())
//}
