//
//  PlayerDetailView.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 17/04/2024.
//

import SwiftUI
import LeStorage

struct PlayerDetailView: View {
    @Environment(Tournament.self) var tournament: Tournament
    @EnvironmentObject var dataStore: DataStore
    @Bindable var player: PlayerRegistration
    @FocusState private var textFieldIsFocus: Bool

    var body: some View {
        Form {
            Section {
                LabeledContent {
                    TextField("Nom", text: $player.lastName)
                        .keyboardType(.alphabet)
                        .multilineTextAlignment(.trailing)
                        .frame(maxWidth: .infinity)
                } label: {
                    Text("Nom")
                }
                            
                LabeledContent {
                    TextField("Prénom", text: $player.firstName)
                        .keyboardType(.alphabet)
                        .multilineTextAlignment(.trailing)
                        .frame(maxWidth: .infinity)
                } label: {
                    Text("Prénom")
                }
                            
                PlayerSexPickerView(player: player)
            }
            
            Section {
                LabeledContent {
                    TextField("Rang", value: $player.rank, format: .number)
                        .keyboardType(.decimalPad)
                        .multilineTextAlignment(.trailing)
                        .frame(maxWidth: .infinity)
                        .focused($textFieldIsFocus)
                } label: {
                    Text("Rang")
                }
            } header: {
                Text("Classement actuel")
            } footer: {
                if player.rank == nil {
                    Text("Classement calculé : " + player.computedRank.formatted())
                }
            }
            
            if player.isMalePlayer() == false && tournament.tournamentCategory == .men, let rank = player.rank {
                Section {
                    let value = PlayerRegistration.addon(for: rank, manMax: tournament.maleUnrankedValue ?? 0, womanMax: tournament.femaleUnrankedValue ?? 0)
                    LabeledContent {
                        Text(value.formatted())
                    } label: {
                        Text("Valeur à rajouter")
                    }
                    LabeledContent {
                        TextField("Rang", value: $player.computedRank, format: .number)
                            .keyboardType(.decimalPad)
                            .multilineTextAlignment(.trailing)
                            .frame(maxWidth: .infinity)
                            .focused($textFieldIsFocus)
                    } label: {
                        Text("Poids re-calculé")
                    }
                } header: {
                    Text("Ré-assimilation")
                } footer: {
                    Text("Calculé en fonction du sexe")
                }
            }
        }
        .scrollDismissesKeyboard(.immediately)
        .onChange(of: player.sex) {
            _save()
        }
        .onChange(of: player.computedRank) {
            player.team()?.updateWeight(inTournamentCategory: tournament.tournamentCategory)
            _save()
        }
        .onChange(of: player.rank) {
            player.setComputedRank(in: tournament)
            player.team()?.updateWeight(inTournamentCategory: tournament.tournamentCategory)
            _save()
        }
        .headerProminence(.increased)
        .navigationTitle("Édition")
        .navigationBarTitleDisplayMode(.inline)
        .toolbarBackground(.visible, for: .navigationBar)
        .toolbar {
            ToolbarItem(placement: .keyboard) {
                Button("Valider") {
                    textFieldIsFocus = false
                }
            }
        }
    }
    
    private func _save() {
        do {
            try dataStore.playerRegistrations.addOrUpdate(instance: player)
        } catch {
            Logger.error(error)
        }
        if let team = player.team() {
            do {
                try dataStore.teamRegistrations.addOrUpdate(instance: team)
            } catch {
                Logger.error(error)
            }
        }
    }
}

//#Preview {
//    PlayerDetailView(player: PlayerRegistration.mock())
//}
