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

import SwiftUI
import LeStorage

struct EditingTeamView: View {
    @EnvironmentObject var dataStore: DataStore
    var team: TeamRegistration
    @State private var registrationDate : Date
    @State private var name: String
    
    init(team: TeamRegistration) {
        self.team = team
        _name = .init(wrappedValue: team.name ?? "")
        _registrationDate = State(wrappedValue: team.registrationDate ?? Date())
    }
    
    var body: some View {
        List {
            Section {
                TextField("Nom de l'équipe", text: $name)
                    .autocorrectionDisabled()
                    .keyboardType(.alphabet)
                    .frame(maxWidth: .infinity)
                    .submitLabel(.done)
                    .onSubmit(of: .text) {
                        let trimmed = name.trimmed
                        if trimmed.isEmpty {
                            team.name = nil
                        } else {
                            team.name = trimmed
                        }
                        
                        _save()
                    }

            }
            Section {
                DatePicker(registrationDate.formatted(.dateTime.weekday()), selection: $registrationDate)
            } header: {
                Text("Date d'inscription")
            }
            
            Section {
                Toggle(isOn: hasArrived) {
                    Text("Équipe sur place")
                }
                /*
                Toggle(isOn: $team.confirmedCall) {
                    Text("Équipe sur place")
                }
                 */
            }
            
            Section {
                RowButtonView("Retirer des poules", role: .destructive) {
                    team.resetGroupeStagePosition()
                    _save()
                }
                .disabled(team.inGroupStage() == false)
            }

            Section {
                RowButtonView("Retirer du tableau", role: .destructive) {
                    team.resetBracketPosition()
                    _save()
                }
                .disabled(team.inRound() == false)
            }
        }
        .onChange(of: registrationDate) {
            team.registrationDate = registrationDate
            _save()
        }
        .headerProminence(.increased)
        .navigationTitle("Édition")
        .navigationBarTitleDisplayMode(.inline)
        .toolbarBackground(.visible, for: .navigationBar)
    }
    
    private var hasArrived: Binding<Bool> {
        Binding {
            team.unsortedPlayers().allSatisfy({ $0.hasArrived })
        } set: { hasArrived in
            team.unsortedPlayers().forEach {
                $0.hasArrived = hasArrived
            }
            do {
                try dataStore.playerRegistrations.addOrUpdate(contentOfs: team.unsortedPlayers())
            } catch {
                Logger.error(error)
            }
        }

    }
    private func _save() {
        do {
            try dataStore.teamRegistrations.addOrUpdate(instance: team)
        } catch {
            Logger.error(error)
        }
    }
}

//#Preview {
//    EditingTeamView(team: TeamRegistration.mock())
//}
