//
//  EventClubSettingsView.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 18/04/2024.
//

import SwiftUI
import LeStorage

struct EventClubSettingsView: View {
    @EnvironmentObject var dataStore: DataStore
    @State private var selectedCourt: Court?
    @State private var showClubDetail: Club?
    var event: Event
    
    var body: some View {
        List {
            if let selectedClub = event.clubObject() {
                
                Section {
                    NavigationLink {
                        ClubsView() { club in
                            _setClub(club: club)
                        }
                    } label: {
                        ClubRowView(club: selectedClub)
                    }
                } header: {
                    Text("Lieu de l'événement")
                } footer: {
                    HStack {
                        Spacer()
                        FooterButtonView("détails du club") {
                            showClubDetail = selectedClub
                        }
                    }
                }
                
                ClubCourtSetupView(club: selectedClub, displayContext: selectedClub.hasBeenCreated(by: StoreCenter.main.userId) ? .edition : .lockedForEditing, selectedCourt: $selectedCourt)

            } else {
                Section {
                    ContentUnavailableView {
                        Text("Aucun club associé à votre tournoi")
                    } description: {
                        Text("Vous avez besoin d'associer un club à votre tournoi pour pouvoir publier celui-ci sur Padel Club.")
                    } actions: {
                        NavigationLink {
                            ClubsView() { club in
                                _setClub(club: club)
                            }
                        } label: {
                            Text("Choisir un club")
                        }
                    }
                }
            }
        }
        .navigationDestination(item: $showClubDetail) { club in
            ClubDetailView(club: club, displayContext: club.hasBeenCreated(by: StoreCenter.main.userId) ? .edition : .lockedForEditing)
        }
        .navigationDestination(item: $selectedCourt) { court in
            CourtView(court: court)
        }
    }
    
    private func _setClub(club: Club) {
        event.club = club.id
        do {
            try dataStore.events.addOrUpdate(instance: event)
        } catch {
            Logger.error(error)
        }
    }
}

//#Preview {
//    TournamentClubSettingsView()
//}
