//
//  LoserRoundScheduleEditorView.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 14/04/2024.
//

import SwiftUI
import LeStorage

struct LoserRoundScheduleEditorView: View {
    @EnvironmentObject var dataStore: DataStore
    
    var upperRound: Round
    var tournament: Tournament
    var loserRounds: [Round]
    @State private var startDate: Date
    @State private var matchFormat: MatchFormat

    init(upperRound: Round, tournament: Tournament) {
        self.upperRound = upperRound
        self.tournament = tournament
        let _loserRounds = upperRound.loserRounds()
        self.loserRounds = _loserRounds
        self._startDate = State(wrappedValue: _loserRounds.first(where: { $0.startDate != nil })?.startDate ?? _loserRounds.first(where: { $0.isDisabled() == false })?.enabledMatches().first?.startDate ?? tournament.startDate)
        self._matchFormat = State(wrappedValue: _loserRounds.first?.matchFormat ?? upperRound.matchFormat)
    }
    
    var body: some View {
        List {
            MatchFormatPickingView(matchFormat: $matchFormat) {
                await _updateSchedule()
            }
            
            DatePickingView(title: "Horaire minimum", startDate: $startDate, currentDate: .constant(nil), duration: matchFormat.getEstimatedDuration(tournament.additionalEstimationDuration)) {
                await _updateSchedule()
            }
            
            let enabledLoserRounds = upperRound.loserRounds().filter({ $0.isDisabled() == false })
            ForEach(enabledLoserRounds.indices, id: \.self) { index in
                let loserRound = enabledLoserRounds[index]
                LoserRoundStepScheduleEditorView(stepIndex: index, round: loserRound, upperRound: upperRound, tournament: tournament)
                    .id(UUID())
            }
        }
        .onChange(of: matchFormat) {
            loserRounds.forEach { round in
                round.updateMatchFormat(matchFormat, checkIfPossible: false, andLoserBracket: true)
            }
            _save()
        }
        .headerProminence(.increased)
        .navigationTitle("Classement " + upperRound.roundTitle())
        .toolbarBackground(.visible, for: .navigationBar)
        .navigationBarTitleDisplayMode(.inline)
    }
    
    private func _updateSchedule() async {
//        let matches = upperRound.loserRounds().flatMap({ round in
//            round.playedMatches()
//        })
//        upperRound.loserRounds().forEach({ round in
//            round.resetFromRoundAllMatchesStartDate()
//        })
//        
//        try? dataStore.matches.addOrUpdate(contentOfs: matches)
//        _save()
        
        let loserRounds = upperRound.loserRounds().filter { $0.isDisabled() == false }
        let scheduler: MatchScheduler? = tournament.matchScheduler()
        scheduler?.updateBracketSchedule(tournament: self.tournament, fromRoundId: loserRounds.first?.id, fromMatchId: nil, startDate: self.startDate)
        loserRounds.first?.startDate = startDate
        _save()
    }
    
    private func _save() {
        do {
            try dataStore.rounds.addOrUpdate(contentOfs: upperRound.loserRounds())
        } catch {
            Logger.error(error)
        }
    }

}
