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

import SwiftUI
import LeStorage

struct EditablePlayerView: View {
    
    enum PlayerEditingOption {
        case payment
        case licenceId
        case name
    }
    
    @EnvironmentObject var dataStore: DataStore
    @Bindable var player: PlayerRegistration
    var editingOptions: [PlayerEditingOption]
    @State private var editedLicenceId = ""
    @State private var shouldPresentLicenceIdEdition: Bool = false
    @State private var presentLastNameUpdate: Bool = false
    @State private var presentFirstNameUpdate: Bool = false

    var body: some View {
        computedPlayerView(player)
            .alert("Numéro de licence", isPresented: $shouldPresentLicenceIdEdition) {
                TextField("Numéro de licence", text: $editedLicenceId)
                    .onSubmit {
                        player.licenceId = editedLicenceId
                        editedLicenceId = ""
                        do {
                            try dataStore.playerRegistrations.addOrUpdate(instance: player)
                        } catch {
                            Logger.error(error)
                        }
                    }
            }
            .alert("Prénom", isPresented: $presentFirstNameUpdate) {
                TextField("Prénom", text: $player.firstName)
                    .onSubmit {
                        do {
                            try dataStore.playerRegistrations.addOrUpdate(instance: player)
                        } catch {
                            Logger.error(error)
                        }
                    }
            }
            .alert("Nom", isPresented: $presentLastNameUpdate) {
                TextField("Nom", text: $player.lastName)
                    .onSubmit {
                        do {
                            try dataStore.playerRegistrations.addOrUpdate(instance: player)
                        } catch {
                            Logger.error(error)
                        }
                    }
            }

    }
    
    @ViewBuilder
    func computedPlayerView(_ player: PlayerRegistration) -> some View {
        VStack(alignment: .leading, spacing: 0.0) {
            ImportedPlayerView(player: player)
//            HStack {
//                Text(player.isImported() ? "importé via beach padel" : "")
//                Text(player.formattedLicense().isLicenseNumber ? "licence valide" : "non valide")
//            }.font(.footnote)
            HStack {
                Menu {
                    Button {
                        player.hasArrived.toggle()
                        do {
                            try dataStore.playerRegistrations.addOrUpdate(instance: player)
                        } catch {
                            Logger.error(error)
                        }
                    } label: {
                        Label("Présent", systemImage: player.hasArrived ? "checkmark.circle" : "circle")
                    }

                    if let number = player.phoneNumber?.replacingOccurrences(of: " ", with: ""), let url = URL(string: "tel:\(number)") {
                        Link(destination: url) {
                            Label("Appeler", systemImage: "phone")
                            Text(number)
                        }
                    }
                    if let number = player.phoneNumber?.replacingOccurrences(of: " ", with: ""), let url = URL(string: "sms:\(number)") {
                        Link(destination: url) {
                            Label("SMS", systemImage: "message")
                            Text(number)
                        }
                    }
                    if let mail = player.email, let url = URL(string: "mailto:\(mail)") {
                        Link(destination: url) {
                            Label("SMS", systemImage: "message")
                            Text(mail)
                        }
                    }

                    if editingOptions.contains(.name) {
                        Divider()
                        Button("Modifier le prénom") {
                            presentFirstNameUpdate = true
                        }
                        Button("Modifier le nom") {
                            presentLastNameUpdate = true
                        }
                    }
                    if editingOptions.contains(.licenceId) {
                        Divider()
                        if let licenseYearValidity = player.tournament()?.licenseYearValidity(), player.isValidLicenseNumber(year: licenseYearValidity) == false, player.licenceId != nil {
                            Button {
                                player.validateLicenceId(licenseYearValidity)
                            } label: {
                                Text("Valider la licence \(licenseYearValidity)")
                            }
                        }
                    }

                    if let license = player.licenceId?.strippedLicense {
                        Button {
                            let pasteboard = UIPasteboard.general
                            pasteboard.string = license
                        } label: {
                            Label("Copier la licence", systemImage: "doc.on.doc")
                        }
                    }
                    
                    Section {
                        Button {
                            editedLicenceId = player.licenceId ?? ""
                            shouldPresentLicenceIdEdition = true
                        } label: {
                            if player.licenceId == nil {
                                Text("Ajouter la licence")
                            } else {
                                Text("Modifier la licence")
                            }
                        }
                        PasteButton(payloadType: String.self) { strings in
                            guard let first = strings.first else { return }
                            player.licenceId = first
                        }
                    } header: {
                        Text("Modification de licence")
                    }
                } label: {
                    Text("Options")
                }
                if editingOptions.contains(.payment) {
                    Spacer()
                    PlayerPayView(player: player)
                }
            }
        }
    }
}
