//
//  LoserRoundStepScheduleEditorView.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 17/04/2024.
//

import SwiftUI
import LeStorage

struct LoserRoundStepScheduleEditorView: View {
    @EnvironmentObject var dataStore: DataStore

    var stepIndex: Int
    var round: Round
    var upperRound: Round
    var tournament: Tournament
    var matches: [Match]
    @State private var startDate: Date
    //@State private var matchFormat: MatchFormat

    init(stepIndex: Int, round: Round, upperRound: Round, tournament: Tournament) {
        self.upperRound = upperRound
        self.tournament = tournament
        self.round = round
        self.stepIndex = stepIndex
        let _matches = upperRound.loserRounds(forRoundIndex: round.index).flatMap({ $0.enabledMatches() })
        self.matches = _matches
        self._startDate = State(wrappedValue: round.startDate ?? _matches.first?.startDate ?? tournament.startDate)
        //self._matchFormat = State(wrappedValue: round.matchFormat)
    }
    
    var body: some View {
        @Bindable var round = round

        DatePickingView(title: "Tour #\(stepIndex + 1)", startDate: $startDate, currentDate: .constant(nil), duration: round.matchFormat.getEstimatedDuration(tournament.additionalEstimationDuration)) {
            await _updateSchedule()
        }

        Section {
            NavigationLink {
                List {
                    ForEach(matches) { match in
                        if match.disabled == false {
                            MatchScheduleEditorView(match: match, tournament: tournament)
                        }
                    }
                }
                .headerProminence(.increased)
                .navigationTitle("Tour #\(stepIndex + 1)")
                .environment(tournament)
            } label: {
                Text("Voir tous les matchs du \((stepIndex + 1).ordinalFormatted()) tour")
            }
        }
        .headerProminence(.increased)
        .onChange(of: round.startDate) {
            _save()
        }
    }
    
    private func _updateSchedule() async {
        tournament.matchScheduler()?.updateBracketSchedule(tournament: tournament, fromRoundId: round.id, fromMatchId: nil, startDate: startDate)
        upperRound.loserRounds(forRoundIndex: round.index).forEach({ round in
            round.startDate = startDate
        })
        _save()
    }
    
    private func _save() {
        do {
            try dataStore.rounds.addOrUpdate(contentOfs: upperRound.loserRounds(forRoundIndex: round.index))
        } catch {
            Logger.error(error)
        }
    }
}
