import SwiftUI

struct AddFileView: View {

    @Environment(\.dismiss)
    private var dismiss: DismissAction

    @EnvironmentObject
    private var content: Content

    @Binding
    var selectedFile: FileResource?

    @State
    private var filesToAdd: [FileToAdd] = []

    init(selectedFile: Binding<FileResource?>) {
        _selectedFile = selectedFile
    }

    var body: some View {
        VStack {
            Text("Select files to add")
                .foregroundStyle(.secondary)
            List {
                ForEach(filesToAdd) { file in
                    FileToAddView(file: file, delete: delete)
                }
            }.frame(minHeight: 300)
            HStack {
                Button("Cancel", role: .cancel) { dismiss() }
                Button("Select more files", action: openFilePanel)
                Button("Add placeholder", action: addPlaceholderFile)
                Button("Add selected", action: importSelectedFiles)
                    .disabled(filesToAdd.isEmpty)
            }
        }
        .padding()
    }

    private func openFilePanel() {
        let panel = NSOpenPanel()

        panel.canChooseFiles = true
        panel.canChooseDirectories = false
        panel.allowsMultipleSelection = true
        panel.showsHiddenFiles = false
        panel.title = "Select files to add"
        panel.prompt = ""

        let response = panel.runModal()
        guard response == .OK else {
            print("Failed to select files to import")
            return
        }

        for url in panel.urls {
            guard !filesToAdd.contains(where: { $0.url == url }) else {
                print("Skipping already selected file \(url.path())")
                continue
            }
            print("Selected file \(url.path())")
            let newFile = FileToAdd(content: content, url: url)
            filesToAdd.append(newFile)
        }
    }

    private func addPlaceholderFile() {
        let newFile = FileToAdd(content: content, externalFile: "placeholder")
        filesToAdd.append(newFile)
    }

    private func delete(file: FileToAdd) {
        guard let index = filesToAdd.firstIndex(of: file) else {
            return
        }
        filesToAdd.remove(at: index)
    }

    private func importSelectedFiles() {
        guard !filesToAdd.isEmpty else {
            dismiss()
            return
        }
        for file in filesToAdd {
            guard file.isSelected else {
                print("Skipping unselected file \(file.uniqueId)")
                continue
            }
            guard !file.idAlreadyExists else {
                print("Skipping existing file \(file.uniqueId)")
                continue
            }
            if let url = file.url {
                guard content.storage.importExternalFile(at: url, fileId: file.uniqueId) else {
                    print("Failed to import file '\(file.uniqueId)' at \(url.path())")
                    return
                }
            }

            let resource = FileResource(
                content: content,
                id: file.uniqueId,
                isExternallyStored: file.url == nil,
                english: "",
                german: "")

            content.add(resource)
            selectedFile = resource
        }
        content.generateMissingVideoThumbnails()
        dismiss()
    }
}

#Preview {
    AddFileView(selectedFile: .constant(nil))
}
