//
//  CoachListView.swift
//  PadelClub
//
//  Created by razmig on 16/10/2024.
//

import SwiftUI
import LeStorage

struct CoachListView: View {
    @Environment(Tournament.self) var tournament
    @State private var coachNames: String
    var team: TeamRegistration

    init(team: TeamRegistration) {
        self.team = team
        _coachNames = .init(wrappedValue: team.comment ?? "")
    }
    
    var body: some View {
        Section {
            HStack {
                TextField("Coach", text: $coachNames)
                    .autocorrectionDisabled()
                    .keyboardType(.alphabet)
                    .frame(maxWidth: .infinity)
                    .submitLabel(.done)
                    .onSubmit(of: .text) {
                        let trimmed = coachNames.prefixTrimmed(200)
                        if trimmed.isEmpty {
                            team.comment = nil
                        } else {
                            team.comment = trimmed
                        }
                        _save()
                    }
                if coachNames.isEmpty == false {
                    FooterButtonView("effacer", role: .destructive) {
                        coachNames = ""
                        team.comment = nil
                        _save()
                    }
                }
            }
        } header: {
            Text("Coachs")
        }
    }
    
    private func _save() {
        do {
            try self.tournament.tournamentStore?.teamRegistrations.addOrUpdate(instance: team)
        } catch {
            Logger.error(error)
        }
    }

}
