//
//  MatchScheduleEditorView.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 10/04/2024.
//

import SwiftUI
import LeStorage

struct MatchScheduleEditorView: View {
    @Bindable var match: Match
    var tournament: Tournament
    @State private var startDate: Date
    @State private var currentDate: Date?

    var tournamentStore: TournamentStore? {
        return self.tournament.tournamentStore
    }
    
    init(match: Match, tournament: Tournament) {
        self.match = match
        self.tournament = tournament
        self._startDate = State(wrappedValue: match.startDate ?? tournament.startDate)
        self._currentDate = State(wrappedValue: match.startDate)
    }
    
    var title: String {
        if let round = match.roundObject {
            return round.roundTitle() + " " + match.matchTitle()
        } else {
            return match.matchTitle()
        }
    }
    
    var body: some View {
        MatchFormatPickingView(matchFormat: $match.matchFormat) {
            await _updateSchedule()
        }

        DatePickingView(title: title, startDate: $startDate, currentDate: $currentDate, duration: match.matchFormat.getEstimatedDuration(tournament.additionalEstimationDuration)) {
            await _updateSchedule()
        }
        .onChange(of: currentDate) {
            match.startDate = currentDate
            _save()
        }
    }
    
    private func _updateSchedule() async {
        let scheduler: MatchScheduler? = tournament.matchScheduler()
        scheduler?.updateBracketSchedule(tournament: tournament, fromRoundId: match.round, fromMatchId: match.id, startDate: startDate)
    }
    
    private func _save() {
        do {
            try tournamentStore?.matches.addOrUpdate(instance: match)
        } catch {
            Logger.error(error)
        }
    }
}

//#Preview {
//    MatchScheduleEditorView(match: Match.mock(), tournament: Tournament.mock())
//}
