//
//  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
    @State private var currentDate: Date?

    var tournamentStore: TournamentStore? {
        return self.tournament.tournamentStore
    }
    
    init(upperRound: Round, tournament: Tournament) {
        self.upperRound = upperRound
        self.tournament = tournament
        let _loserRounds = upperRound.loserRounds()
        self.loserRounds = _loserRounds
        let startDate = _loserRounds.first(where: { $0.startDate != nil })?.startDate ?? _loserRounds.first(where: { $0.isDisabled() == false })?.enabledMatches().first?.startDate
        
        self._startDate = State(wrappedValue: startDate ?? tournament.startDate)
        self._matchFormat = State(wrappedValue: _loserRounds.first?.matchFormat ?? upperRound.matchFormat)
        self._currentDate = State(wrappedValue: startDate)
    }
    
    var body: some View {
        List {
            MatchFormatPickingView(title: "Format des tours par défault", matchFormat: $matchFormat) {
                await _updateSchedule()
            }
            
            DatePickingView(title: "Horaire minimum", startDate: $startDate, currentDate: $currentDate, duration: matchFormat.getEstimatedDuration(tournament.additionalEstimationDuration)) {
                await _updateSchedule()
            }
            .onChange(of: currentDate) {
                let enabledLoserRounds = upperRound.loserRounds().filter({ $0.isDisabled() == false })
                for loserRound in enabledLoserRounds {
                    loserRound.startDate = currentDate
                }

                _save()
            }
            
            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 self.tournamentStore?.rounds.addOrUpdate(contentOfs: upperRound.loserRounds())
        } catch {
            Logger.error(error)
        }
    }

}
