import SwiftUI
import SFSafeSymbols

struct FolderOnDiskPropertyView: View {

    let title: LocalizedStringKey

    @Binding
    var folder: SecurityBookmark?

    let footer: LocalizedStringKey

    let update: (URL) -> Void

    init(title: LocalizedStringKey, folder: Binding<SecurityBookmark?>, footer: LocalizedStringKey, update: @escaping (URL) -> Void) {
        self.title = title
        self._folder = folder
        self.footer = footer
        self.update = update
    }

    var body: some View {
        VStack(alignment: .leading) {

            HStack(alignment: .firstTextBaseline) {
                Text(title)
                    .font(.headline)
                if folder == nil || folder?.isStale == true {
                    Image(systemSymbol: .exclamationmarkTriangle)
                        .foregroundStyle(.yellow)
                }
                Spacer()
                Button("Select") {
                    guard let url = openFolderSelectionPanel() else {
                        return
                    }
                    DispatchQueue.main.async {
                        update(url)
                    }
                }
            }
            Text(folder?.url.path() ?? "No folder selected")
                .padding(.bottom, 5)
            Text(footer)
                .foregroundStyle(.secondary)
                .padding(.bottom)
        }
    }

    private func openFolderSelectionPanel() -> URL? {
        let panel = NSOpenPanel()
        // Sets up so user can only select a single directory
        panel.canChooseFiles = false
        panel.canChooseDirectories = true
        panel.allowsMultipleSelection = false
        panel.showsHiddenFiles = false
        panel.title = "Select directory"
        //panel.prompt = "Select Directory"

        let response = panel.runModal()
        guard response == .OK else {
            return nil
        }
        guard let url = panel.url else {
            return nil
        }
        return url
    }
}
