//
//  ContentView.swift
//  vectorsearch
//
//  Created by Du Qingjie on 2024/08/31.
//
import SwiftUI

struct ContentView: View {
    @ObservedObject var viewModel: AppViewModel
    
    @StateObject private var languageManager = LanguageManager()
    @State private var searchText = ""
    @State private var results: [String] = []
    @State private var isFolderConfigPresented = false
    @State private var selectedLanguage = Locale.current.language.languageCode?.identifier ?? "en"
    //@State private var statusMessage: String = NSLocalizedString("status_ready", comment: "")
    
    var body: some View {
        VStack {
            HStack {
                TextField(NSLocalizedString("Search", comment: "Search"), text: $searchText)
                    .textFieldStyle(PlainTextFieldStyle()) // Flat, macOS-like style
                    .padding()
                    .onSubmit {
                        performSearch(query: searchText)
                    }
                Button(NSLocalizedString("Search", comment: "Search")) {
                    performSearch(query: searchText)
                }
                .buttonStyle(PlainButtonStyle()) // Flat button style for macOS
                .padding(.horizontal)

                Button(NSLocalizedString("Folder Config", comment: "Folder Config")) {
                    isFolderConfigPresented = true
                }
                .buttonStyle(PlainButtonStyle()) // Flat button style
                .padding(.horizontal)
                .sheet(isPresented: $isFolderConfigPresented) {
                    FolderConfigView(isPresented: $isFolderConfigPresented)
                }
                
                Picker("", selection: $languageManager.currentLanguage) {
                    Text(NSLocalizedString("English", comment: "English")).tag("en")
                    Text(NSLocalizedString("Japanese", comment: "Japanese")).tag("ja")
                }
                .labelsHidden()
                .pickerStyle(SegmentedPickerStyle()) // Use segmented picker for macOS-like feel
            }
            .padding()
            
            List(results, id: \.self) { result in
                HStack {
                    Text(result).textSelection(.enabled)
                    Spacer()
                    Button(action: {
                        openFile(path: result)
                    }) {
                        Text(NSLocalizedString("Open", comment: "Open"))
                    }
                    .buttonStyle(LinkButtonStyle()) // macOS-native link style
                    Button(action: {
                        showInFinder(path: result)
                    }) {
                        Text(NSLocalizedString("Show in Finder", comment: "Show in Finder"))
                    }
                    .buttonStyle(LinkButtonStyle())
                }
            }
            .listStyle(PlainListStyle()) // Minimalist list style
            .padding(.horizontal)
            
            Text(viewModel.statusMessage)
                .font(.footnote)
                .padding(.top, 10)
                .padding(.bottom)
        }
        .frame(minWidth: 800, minHeight: 600)
        .onAppear(){
            if let window = NSApplication.shared.windows.first {
                window.title = "v-search"
            }
        }
    }
    
    func performSearch(query: String) {
        Task {
            viewModel.statusMessage = NSLocalizedString("status_search_start", comment: "")
            let searchResults = await VectorManager.shared.search(query: query)
            results = searchResults.map { $0.id }
            viewModel.statusMessage = NSLocalizedString("status_search_completed", comment: "")
        }
    }

    func openFile(path: String) {
        let url = URL(fileURLWithPath: path)
        if let folder = findContainingFolder(for: url) {
            let bookmark = UserDefaults.standard.data(forKey: folder.path)
            var isStale = false
            do {
                let restoredURL = try URL(resolvingBookmarkData: bookmark!, options: [.withSecurityScope], relativeTo: nil, bookmarkDataIsStale: &isStale)
                if restoredURL.startAccessingSecurityScopedResource() {
                    NSWorkspace.shared.open(url)
                    restoredURL.stopAccessingSecurityScopedResource()
                }
            } catch {
                Logger.shared.err("Error resolving bookmark: \(error)")
            }
        } 
    }

    func showInFinder(path: String) {
        let url = URL(fileURLWithPath: path)
        NSWorkspace.shared.activateFileViewerSelecting([url])
    }
    
    func findContainingFolder(for fileURL: URL) -> URL? {
        if let savedFolders = UserDefaults.standard.array(forKey: "savedFolders") as? [String] {
            for folderPath in savedFolders {
                let folderURL = URL(fileURLWithPath: folderPath)
                if fileURL.path.hasPrefix(folderURL.path) {
                    return folderURL
                }
            }
        }
        return nil
    }
}

/*struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}*/
