//
//  CreateClubView.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 20/03/2024.
//

import SwiftUI
import LeStorage

struct CreateClubView: View {
    @EnvironmentObject var dataStore: DataStore
    @Environment(\.dismiss) var dismiss
    var club: Club
    var selection: ((Club) -> ())? = nil
    
    @State private var validationInProgress: Bool = false
    
    var body: some View {
        NavigationStack {
            ClubDetailView(club: club, displayContext: .addition, selection: selection)
                .toolbar {
                    ToolbarItem(placement: .cancellationAction) {
                        Button("Annuler", role: .cancel) {
                            dismiss()
                        }
                    }
                    ToolbarItem(placement: .confirmationAction) {
                        if validationInProgress {
                            ProgressView()
                        } else {
                            ButtonValidateView {
                                validationInProgress = true
                            }
                            .disabled(club.isValid == false)
                        }
                    }
                }
                .onChange(of: validationInProgress) {
                    if validationInProgress {
                        Task {
                            do {
                                try await dataStore.clubs.loadDataFromServerIfAllowed()
                            } catch {
                                Logger.error(error)
                            }
                            
                            let existingOrCreatedClub = Club.findOrCreate(name: club.name, code: club.code, city: club.city, zipCode: club.zipCode)
                            
                            //update existing club if rights ok / freshly created club with data input from user
                            if existingOrCreatedClub.hasBeenCreated(by: Store.main.userId) {
                                existingOrCreatedClub.update(fromClub: club)
                            }
                            
                            do {
                                try dataStore.clubs.addOrUpdate(instance: existingOrCreatedClub)
                            } catch {
                                Logger.error(error)
                            }
                            
                            //save into user
                            if dataStore.user.clubs.contains(where: { $0 == existingOrCreatedClub.id }) == false {
                                dataStore.user.clubs.append(existingOrCreatedClub.id)
                                self.dataStore.saveUser()
                            }
                            dismiss()
                            selection?(existingOrCreatedClub)
                        }
                    }
                }
        }
    }
}

//#Preview {
//    CreateClubView(club: Club.mock())
//        .environmentObject(DataStore.shared)
//}
