//
//  FolderConfigView.swift
//  vectorsearch
//
//  Created by Du Qingjie on 2024/08/31.
//

import SwiftUI

struct FolderConfigView: View {
    @Binding var isPresented: Bool
    
    @State private var folders: [String] = UserDefaults.standard.stringArray(forKey: "savedFolders") ?? []
    @State private var windowSize: CGSize = .zero

    @State private var showDeleteConfirmation = false
    @State private var folderToDelete: String?

    var body: some View {
        VStack {
            // Header with title and close button
            HStack {
                Text(NSLocalizedString("Folder Configuration", comment: "Folder Configuration"))
                    .font(.headline)
                    .padding(.leading) // Align headline with flat style
                
                Spacer()

                Button(action: {
                    isPresented = false
                }) {
                    Image(systemName: "xmark.circle.fill")
                        .resizable()
                        .frame(width: 18, height: 18) // Smaller, more macOS-like size
                        .foregroundColor(.gray)
                }
                .buttonStyle(PlainButtonStyle()) // Flat button style
            }
            .padding([.top, .trailing])

            // Folder list
            List {
                ForEach(folders, id: \.self) { folder in
                    HStack {
                        Text(folder)
                        Spacer()
                        Button(action: {
                            folderToDelete = folder
                            showDeleteConfirmation = true
                        }) {
                            Image(systemName: "xmark.circle.fill")
                                .resizable()
                                .frame(width: 18, height: 18) // Smaller, minimalist design
                                .foregroundColor(.red)
                        }
                        .buttonStyle(PlainButtonStyle()) // Flat button style
                    }
                }
            }
            .listStyle(PlainListStyle()) // Flat list style
            
            HStack {
                // Add Folder button
                Button(NSLocalizedString("Add Folder", comment: "Add Folder")) {
                    addFolder()
                }
                .buttonStyle(PlainButtonStyle()) // Flat button style
                .padding(.top)
            }
        }
        .padding()
        .frame(width: windowSize.width * 0.8, height: windowSize.height * 0.8) // 80% of main window size
        .onAppear {
            updateWindowSize()
        }
        .alert(isPresented: $showDeleteConfirmation) {
            Alert(
                title: Text(NSLocalizedString("Delete Folder", comment: "Delete Folder")),
                message: Text(String.localizedStringWithFormat(NSLocalizedString("delete_folder_message", comment: ""), folderToDelete ?? "")),
                primaryButton: .destructive(Text(NSLocalizedString("Delete", comment: ""))) {
                    if let folder = folderToDelete {
                        deleteFolder(path: folder)
                    }
                },
                secondaryButton: .cancel(Text(NSLocalizedString("Cancel", comment: "")))
            )
        }
    }

    func updateWindowSize() {
        if let window = NSApplication.shared.windows.first {
            windowSize = window.frame.size
        }
    }

    func addFolder() {
        let panel = NSOpenPanel()
        panel.canChooseDirectories = true
        panel.canChooseFiles = false
        panel.allowsMultipleSelection = true
        panel.prompt = NSLocalizedString("Select Folder", comment: "")

        if panel.runModal() == .OK {
            for url in panel.urls {
                if !folders.contains(url.path) {
                    folders.append(url.path)
                    saveBookmark(for: url)
                }
            }
            saveFolders()
        }
    }

    func deleteFolder(path: String) {
        VectorManager.shared.deleteFileItem(path: path)
        folders.removeAll(where: { $0 == path })
        saveFolders()
    }

    func saveFolders() {
        UserDefaults.standard.setValue(folders, forKey: "savedFolders")
        // VectorManager.shared.scanDirectories() if needed
    }
    
    func saveBookmark(for folderURL: URL) {
        do {
            let bookmarkData = try folderURL.bookmarkData(options: .withSecurityScope, includingResourceValuesForKeys: nil, relativeTo: nil)
            UserDefaults.standard.set(bookmarkData, forKey: folderURL.path)
        } catch {
            Logger.shared.err("Error creating bookmark: \(error)")
        }
    }
}
