//
//  EventCreationView.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 22/03/2024.
//

import SwiftUI
import TipKit
import LeStorage

struct EventCreationView: View {
    @Environment(\.dismiss) private var dismiss
    @EnvironmentObject var dataStore: DataStore
    @Environment(NavigationViewModel.self) private var navigation: NavigationViewModel
    @State private var eventType: EventType = .approvedTournament
    @State private var animationType: AnimationType = .upAndDown
    @State var startingDate: Date = Date().tomorrowAtNine
    @State private var duration: Int = 3
    @State private var eventName: String = ""
    @State var tournaments: [Tournament] = []
    @State var selectedClub: Club?
    @FocusState private var textFieldIsFocus: Bool

    let multiTournamentsEventTip = MultiTournamentsEventTip()
    
    var body: some View {
        NavigationStack {
            Form {
//                Section {
//                    Picker(selection: $eventType) {
//                        ForEach(EventType.allCases) { eventType in
//                            Text(eventType.localizedLabel())
//                        }
//                    } label: {
//                        Text("Type")
//                    }
//                }
                
                Section {
                    DatePicker(selection: $startingDate) {
                        Text(startingDate.formatted(.dateTime.weekday(.wide)).capitalized)
                    }
                    
                    if eventType == .approvedTournament {
                        LabeledContent {
                            StepperView(count: $duration, minimum: 1)
                        } label: {
                            Text("Durée")
                            Text("\(duration) jour" + duration.pluralSuffix)
                        }
                    }
                    
                    NavigationLink {
                        ClubsView() { club in
                            print("club", club.acronym)
                            selectedClub = club
                        }
                    } label: {
                        if let selectedClub {
                            ClubRowView(club: selectedClub, displayContext: .selection)
                        } else {
                            Text("Choisir un club")
                        }
                    }
                    
                    TextField("Nom de l'événement", text: $eventName, axis: .vertical)
                        .lineLimit(2)
                        .keyboardType(.alphabet)
                        .multilineTextAlignment(.leading)
                        .frame(maxWidth: .infinity)
                        .focused($textFieldIsFocus)
                    LabeledContent {
                        Text(tournaments.count.formatted())
                    } label: {
                        Text("Nombre d'épreuve")
                    }

                } header: {
                    Text("")
                }
                
                switch eventType {
                case .approvedTournament:
                    approvedTournamentEditorView
                case .friendlyTournament:
                    approvedTournamentEditorView
                case .simulation:
                    approvedTournamentEditorView
                case .animation:
                    animationEditorView
                }
            }
            .toolbar {
                if textFieldIsFocus {
                    ToolbarItem(placement: .keyboard) {
                        HStack {
                            Spacer()
                            Button("Valider") {
                                textFieldIsFocus = false
                            }
                            .buttonStyle(.bordered)
                        }
                    }
                }

                ToolbarItem(placement: .cancellationAction) {
                    Button("Annuler", role: .cancel) {
                        dismiss()
                    }
                }
                
                ToolbarItem(placement: .topBarTrailing) {
                    ButtonValidateView {
                        _validate()
                    }
                    .disabled(tournaments.isEmpty)
                }
            }
            .navigationTitle("Nouvel événement")
            .navigationBarTitleDisplayMode(.inline)
            .toolbarBackground(.visible, for: .navigationBar)
            .onAppear {
                if selectedClub == nil {
                    selectedClub = dataStore.user.clubsObjects().first
                }
            }
        }
    }
    
    private func _validate() {
        let event = Event(creator: Store.main.userId, name: eventName)
        event.club = selectedClub?.id
        tournaments.forEach { tournament in
            tournament.event = event.id
        }
        
        do {
            try dataStore.events.addOrUpdate(instance: event)
        } catch {
            Logger.error(error)
        }

        tournaments.forEach { tournament in
            tournament.courtCount = selectedClub?.courtCount ?? 2
            tournament.startDate = startingDate
            tournament.dayDuration = duration
            tournament.setupFederalSettings()
        }
        
        do {
            try dataStore.tournaments.addOrUpdate(contentOfs: tournaments)
        } catch {
            Logger.error(error)
        }

        dismiss()
        navigation.path.append(tournaments.first!)
    }
    
    @ViewBuilder
    private var approvedTournamentEditorView: some View {
        ForEach(tournaments.indices, id: \.self) { index in
            let tournament = tournaments[index]
            Section {
                TournamentConfigurationView(tournament: tournament)
            } header: {
                if tournaments.count > 1 {
                    HStack {
                        Spacer()
                        FooterButtonView("effacer") {
                            tournaments.removeAll(where: { $0 == tournament })
                        }
                        .textCase(nil)
                    }
                }
            } footer: {
                if index == tournaments.count - 1 {
                    HStack {
                        Spacer()
                        FooterButtonView("Ajouter une \((tournaments.count + 1).ordinalFormatted()) épreuve") {
                            let tournament = Tournament.newEmptyInstance()
                            self.tournaments.append(tournament)
                        }
                        .popoverTip(multiTournamentsEventTip)
                    }
                }
            }
        }
    }
    
    @ViewBuilder
    var animationEditorView: some View {
        Section {
            Picker(selection: $animationType) {
                ForEach(AnimationType.allCases) { animationType in
                    Text(animationType.localizedLabel()).tag(animationType)
                }
            } label: {
                Text("Type")
            }.pickerStyle(.menu)
        }
        Section {
            Text(animationType.descriptionLabel)
        }
    }
    

}

//#Preview {
//    EventCreationView()
//        .environmentObject(DataStore.shared)
//}
