import PhotosUI
import SwiftUI

struct LibraryView: View {
    @EnvironmentObject private var library: SourceLibrary
    @State private var photosSelection: [PhotosPickerItem] = []
    @State private var showingFileImporter = false
    @State private var showingFolderImporter = false
    @State private var relinkTarget: SourceClip?
    @State private var playbackClip: SourceClip?

    var body: some View {
        NavigationStack {
            List {
                if library.clips.isEmpty {
                    ContentUnavailableView(
                        "No clips yet",
                        systemImage: "film",
                        description: Text("Import from Files (external drive) or Photos. Clips are referenced in place, never copied.")
                    )
                } else {
                    Section("Source clips") {
                        ForEach(library.clips) { clip in
                            ClipRowView(
                                clip: clip,
                                availability: library.availability[clip.id] ?? .unknown,
                                onLocate: { relinkTarget = clip },
                                onPlay: { playbackClip = clip }
                            )
                            .contextMenu {
                                if clip.previousRef != nil {
                                    Button("Undo relink") { library.undoRelink(clipID: clip.id) }
                                }
                                Button(clip.isDebugBroken ? "Clear simulated break" : "Simulate broken reference") {
                                    library.toggleSimulatedBroken(clipID: clip.id)
                                }
                            }
                        }
                        .onDelete { library.deleteClips(at: $0) }
                    }
                }
                Section {
                    ForEach(library.folders) { folder in
                        Label(folder.displayName, systemImage: "folder")
                    }
                    .onDelete { offsets in
                        offsets.map { library.folders[$0] }.forEach(library.removeFolder)
                    }
                    Button {
                        showingFolderImporter = true
                    } label: {
                        Label("Grant folder access…", systemImage: "folder.badge.plus")
                    }
                } header: {
                    Text("Folders for relink scans")
                } footer: {
                    Text("Grant a folder once and the app can silently rescan it to find moved clips.")
                }
            }
            .navigationTitle("Source Library")
            .toolbar {
                ToolbarItemGroup(placement: .topBarTrailing) {
                    PhotosPicker(selection: $photosSelection, matching: .videos, photoLibrary: .shared()) {
                        Label("Import from Photos", systemImage: "photo.on.rectangle")
                    }
                    Button {
                        showingFileImporter = true
                    } label: {
                        Label("Import from Files", systemImage: "externaldrive.badge.plus")
                    }
                    Button {
                        Task { await library.refreshAvailability() }
                    } label: {
                        Label("Refresh", systemImage: "arrow.clockwise")
                    }
                }
            }
            .fileImporter(
                isPresented: $showingFileImporter,
                allowedContentTypes: [.movie, .video],
                allowsMultipleSelection: true
            ) { result in
                if case .success(let urls) = result {
                    Task { await library.importFiles(at: urls) }
                }
            }
            .background {
                // fileImporter can only present one panel per attachment point,
                // so the folder importer hangs off a separate view.
                Color.clear
                    .fileImporter(
                        isPresented: $showingFolderImporter,
                        allowedContentTypes: [.folder]
                    ) { result in
                        if case .success(let url) = result {
                            library.addFolder(url: url)
                        }
                    }
            }
            .onChange(of: photosSelection) { _, items in
                guard !items.isEmpty else { return }
                let picked = items
                photosSelection = []
                Task { await library.importPhotosItems(picked) }
            }
            .sheet(item: $relinkTarget) { clip in
                RelinkSheet(clip: clip)
                    .environmentObject(library)
            }
            .sheet(item: $playbackClip, onDismiss: { library.endPlayback() }) { clip in
                PlayerSheet(clip: clip)
                    .environmentObject(library)
            }
            .alert("Error", isPresented: errorBinding) {
                Button("OK") { library.lastError = nil }
            } message: {
                Text(library.lastError ?? "")
            }
        }
    }

    private var errorBinding: Binding<Bool> {
        Binding(
            get: { library.lastError != nil },
            set: { if !$0 { library.lastError = nil } }
        )
    }
}
