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

import SwiftUI
import LeStorage

struct TournamentClubSettingsView: View {
    @Environment(Tournament.self) private var tournament: Tournament
    @EnvironmentObject var dataStore: DataStore
    @State private var selectedCourt: Court?
    @State private var showClubDetail: Club?
    
    var body: some View {
        @Bindable var tournament = tournament
        List {
            let event = tournament.eventObject()
            let selectedClub = event?.clubObject()
            Section {
                NavigationLink {
                    ClubsView() { club in
                        if let event {
                            event.club = club.id
                            do {
                                try dataStore.events.addOrUpdate(instance: event)
                            } catch {
                                Logger.error(error)
                            }
                        }
                    }
                } label: {
                    if let selectedClub {
                        ClubRowView(club: selectedClub)
                    } else {
                        Text("Choisir un club")
                    }
                }
            } header: {
                Text("Lieu du tournoi")
            } footer: {
                HStack {
                    Spacer()
                    FooterButtonView("détails du club") {
                        showClubDetail = selectedClub
                    }
                }
            }

            
            Section {
                TournamentFieldsManagerView(localizedStringKey: "Terrains pour le tournoi", count: $tournament.courtCount)
                    .onChange(of: tournament.courtCount) {
                        do {
                            try dataStore.tournaments.addOrUpdate(instance: tournament)
                        } catch {
                            Logger.error(error)
                        }
                    }
                
                if let event = tournament.eventObject() {
                    NavigationLink {
                        CourtAvailabilitySettingsView(event: event)
                            .environment(tournament)
                    } label: {
                        Text("Préciser la disponibilité des terrains")
                    }
                }
            } footer: {
                if let club = tournament.club() {
                    if tournament.courtCount < club.courtCount {
                        let plural = tournament.courtCount.pluralSuffix
                        let verb = tournament.courtCount > 1 ? "seront" : "sera"
                        Text("En réduisant les terrains maximum, seul\(plural) le\(plural) \(tournament.courtCount) premier\(plural) terrain\(plural) \(verb) utilisé\(plural)") + Text(", par contre, si vous augmentez le nombre de terrains, vous pourrez plutôt préciser quel terrain n'est pas disponible.")
                    } else if tournament.courtCount > club.courtCount {
                        let isCreatedByUser = club.hasBeenCreated(by: Store.main.userId)
                        Button {
                            do {
                                club.courtCount = tournament.courtCount
                                try dataStore.clubs.addOrUpdate(instance: club)
                            } catch {
                                Logger.error(error)
                            }
                        } label: {
                            if isCreatedByUser {
                                Text("Vous avez indiqué plus de terrains dans ce tournoi que dans le club.")
                                + Text("Mettre à jour le club ?").underline().foregroundStyle(.master)
                            } else {
                                Label("Vous avez indiqué plus de terrains dans ce tournoi que dans le club.", systemImage: "exclamationmark.triangle.fill").foregroundStyle(.logoRed)
                            }
                        }
                        .buttonStyle(.plain)
                        .disabled(isCreatedByUser == false)
                    }
                }
            }
            

            
            if let selectedClub {
                ClubCourtSetupView(club: selectedClub, displayContext: selectedClub.hasBeenCreated(by: Store.main.userId) ? .edition : .lockedForEditing, selectedCourt: $selectedCourt)
                    .onChange(of: selectedClub.courtCount) {
                        tournament.courtCount = max(tournament.courtCount, selectedClub.courtCount)
                        do {
                            try dataStore.tournaments.addOrUpdate(instance: tournament)
                        } catch {
                            Logger.error(error)
                        }
                    }
            }
        }
        .navigationDestination(item: $showClubDetail) { club in
            ClubDetailView(club: club, displayContext: club.hasBeenCreated(by: Store.main.userId) ? .edition : .lockedForEditing)
        }
        .navigationDestination(item: $selectedCourt) { court in
            CourtView(court: court)
        }
    }
}

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