import SwiftUI
import SwiftData

struct SettingsView: View {
    @Environment(\.modelContext) private var modelContext
    @State private var footprint: Int64 = 0
    @State private var purgeCount = 0
    @State private var confirmClear = false
    @State private var message: String?

    private var store: LibraryStore { LibraryStore(modelContext: modelContext) }

    var body: some View {
        Form {
            Section("资料库") {
                LabeledContent("路径") {
                    Text(FileLibrary.libraryRootURL.path)
                        .font(.caption.monospaced())
                        .textSelection(.enabled)
                }
                LabeledContent("占用") {
                    Text(byteString(footprint))
                }
                Button("清理失效目录条目") {
                    purgeCount = store.purgeOrphanCatalogRows()
                    message = "已清理 \(purgeCount) 条"
                    refresh()
                }
                Button("清空资料库", role: .destructive) {
                    confirmClear = true
                }
            }

            Section("关于") {
                LabeledContent("应用", value: "StudyDeck")
                LabeledContent("平台", value: "iPadOS · SwiftUI + SwiftData")
                Text("主导入路径为局域网 HTTP 上传。服务仅前台可用，请在可信局域网使用。")
                    .font(.footnote)
                    .foregroundStyle(.secondary)
            }

            if let message {
                Section {
                    Text(message).foregroundStyle(.secondary)
                }
            }
        }
        .navigationTitle("Settings")
        .onAppear(perform: refresh)
        .confirmationDialog("确认清空 Documents/library 与目录元数据？", isPresented: $confirmClear, titleVisibility: .visible) {
            Button("清空", role: .destructive) { clearLibrary() }
            Button("取消", role: .cancel) {}
        }
    }

    private func refresh() {
        footprint = FileLibrary.storageFootprintBytes()
    }

    private func clearLibrary() {
        do {
            try FileLibrary.clearLibraryContents()
            let entries = (try? modelContext.fetch(FetchDescriptor<CatalogEntry>())) ?? []
            for entry in entries {
                modelContext.delete(entry)
            }
            try? modelContext.save()
            message = "资料库已清空"
            refresh()
        } catch {
            message = error.localizedDescription
        }
    }

    private func byteString(_ bytes: Int64) -> String {
        ByteCountFormatter.string(fromByteCount: bytes, countStyle: .file)
    }
}
