//
//  EventSettingsView.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 17/05/2024.
//

import SwiftUI
import LeStorage

struct EventSettingsView: View {
    @EnvironmentObject var dataStore: DataStore
    @Bindable var event: Event
    @State private var eventName: String = ""
    @FocusState private var textFieldIsFocus: Bool
    @State private var pageLink: PageLink = .teams
    
    func eventLinksPasteData() -> String {
        let tournaments = event.tournaments
        var link = [String]()
        link.append(event.eventTitle())
        
        link.append("\n\n")
        link.append("Retrouvez toutes les infos en suivant le\(tournaments.count.pluralSuffix) lien\(tournaments.count.pluralSuffix) ci-dessous :")
        link.append("\n\n")
        
        link.append(tournaments.compactMap({ tournament in
            if let url = tournament.shareURL(pageLink) {
                var tournamentLink = [String]()
                tournamentLink.append(tournament.tournamentTitle())
                tournamentLink.append(url.absoluteString)
                return tournamentLink.joined(separator: "\n")
            } else {
                return nil
            }
        }).joined(separator: "\n\n"))
        
        return link.joined()
    }

    init(event: Event) {
        self.event = event
        _eventName = State(wrappedValue: event.name ?? "")
    }
    
    var body: some View {
        Form {
            Section {
                TextField("Nom de l'événement", text: $eventName, axis: .vertical)
                    .lineLimit(2)
                    .keyboardType(.alphabet)
                    .multilineTextAlignment(.leading)
                    .frame(maxWidth: .infinity)
                    .focused($textFieldIsFocus)
            } footer: {
                if eventName.isEmpty == false {
                    FooterButtonView("effacer le nom") {
                        eventName = ""
                        event.name = nil
                        _save()
                    }
                }
            }
            
            if event.club != nil {
                let eventLinksPasteData = eventLinksPasteData()
                Section {
                    Text(eventLinksPasteData)
                        .italic()
                        .multilineTextAlignment(.leading)
                    
                    let links : [PageLink] = [.teams, .summons, .groupStages, .matches, .rankings]
                    Picker(selection: $pageLink) {
                        ForEach(links) { pageLink in
                            Text(pageLink.localizedLabel()).tag(pageLink)
                        }
                    } label: {
                        Text("Choisir une page en particulier")
                    }
                    .pickerStyle(.menu)
                    
                    ShareLink("Partagez ce message", item: eventLinksPasteData)
                } header: {
                    Text("Liens à partager")
                }
            }
        }
        .toolbar {
            if textFieldIsFocus {
                ToolbarItem(placement: .keyboard) {
                    HStack {
                        Spacer()
                        Button("Valider") {
                            textFieldIsFocus = false
                            if eventName.trimmed.isEmpty == false {
                                event.name = eventName.trimmed
                            } else {
                                event.name = nil
                            }
                            _save()
                        }
                        .buttonStyle(.bordered)
                    }
                }
            }
        }
    }
    
    private func _save() {
        do {
            try dataStore.events.addOrUpdate(instance: event)
        } catch {
            Logger.error(error)
        }
    }
}
