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

import SwiftUI

protocol Schedulable: Identifiable {
    var startDate: Date? { get set }
    var matchFormat: MatchFormat { get set }
    func playedMatches() -> [Match]
    func titleLabel() -> String
}

extension Schedulable {
    func getStartDate() -> Date? {
        return startDate ?? playedMatches().first?.startDate
    }
}

enum ScheduleDestination: String, Identifiable, Selectable, Equatable {
    static func == (lhs: ScheduleDestination, rhs: ScheduleDestination) -> Bool {
        return lhs.id == rhs.id
    }

    var id: String { self.rawValue }
    
    case planning
    case scheduleGroupStage
    case scheduleBracket
    
    func selectionLabel() -> String {
        switch self {
        case .scheduleGroupStage:
            return "Poules"
        case .scheduleBracket:
            return "Tableau"
        case .planning:
            return "Prog."
        }
    }
    
    func badgeValue() -> Int? {
        return nil
    }
    
    func badgeValueColor() -> Color? {
        return nil
    }
    
    func badgeImage() -> Badge? {
        return nil
    }

}

struct TournamentScheduleView: View {
    var tournament: Tournament
    @State private var selectedScheduleDestination: ScheduleDestination? = .planning
    let allDestinations: [ScheduleDestination]
    
    init(tournament: Tournament) {
        self.tournament = tournament
        var destinations = [ScheduleDestination.planning]
        if tournament.groupStages().isEmpty == false {
            destinations.append(.scheduleGroupStage)
        }
        if tournament.rounds().isEmpty == false {
            destinations.append(.scheduleBracket)
        }
        self.allDestinations = destinations
    }
    
    var body: some View {
        VStack(spacing: 0) {
            GenericDestinationPickerView(selectedDestination: $selectedScheduleDestination, destinations: allDestinations, nilDestinationIsValid: true)
            switch selectedScheduleDestination {
            case .none:
                PlanningSettingsView(tournament: tournament)
            case .some(let selectedSchedule):
                switch selectedSchedule {
                case .scheduleGroupStage:
                    SchedulerView(tournament: tournament, destination: selectedSchedule)
                case .scheduleBracket:
                    SchedulerView(tournament: tournament, destination: selectedSchedule)
                case .planning:
                    PlanningView(matches: tournament.allMatches(), selectedScheduleDestination: $selectedScheduleDestination)
                }
            }
        }
        .navigationBarTitleDisplayMode(.inline)
        .toolbarBackground(.visible, for: .navigationBar)
        .navigationTitle("Horaires")
    }
}

//#Preview {
//    TournamentScheduleView(tournament: Tournament.mock())
//}
