import SwiftUI

struct DraftsListView: View {
    @EnvironmentObject private var store: DraftStore
    @EnvironmentObject private var library: SourceLibrary

    var body: some View {
        NavigationStack {
            List {
                if store.drafts.isEmpty {
                    ContentUnavailableView(
                        "No drafts yet",
                        systemImage: "square.stack",
                        description: Text("A draft is a tiny recipe referencing your source clips — duplicating one never copies video.")
                    )
                } else {
                    ForEach(store.drafts) { draft in
                        NavigationLink(value: draft) {
                            draftRow(draft)
                        }
                        .contextMenu {
                            Button {
                                store.duplicate(draft)
                            } label: {
                                Label("Save As New Draft", systemImage: "plus.square.on.square")
                            }
                            Button(role: .destructive) {
                                store.delete(draft)
                            } label: {
                                Label("Delete", systemImage: "trash")
                            }
                        }
                    }
                    .onDelete { offsets in
                        offsets.map { store.drafts[$0] }.forEach(store.delete)
                    }
                }
            }
            .navigationTitle("Drafts")
            .navigationDestination(for: Draft.self) { draft in
                DraftEditorView(draft: draft)
            }
            .toolbar {
                Button {
                    _ = store.create(name: "Draft \(store.drafts.count + 1)")
                } label: {
                    Label("New Draft", systemImage: "plus")
                }
            }
        }
    }

    private func draftRow(_ draft: Draft) -> some View {
        VStack(alignment: .leading, spacing: 4) {
            Text(draft.name)
                .font(.headline)
            Text("\(draft.clips.count) clips · \(timeString(draft.totalDuration)) · \(draft.modifiedAt.formatted(date: .abbreviated, time: .shortened))")
                .font(.caption)
                .foregroundStyle(.secondary)
            if hasMissingSource(draft) {
                Label("Some source clips are missing — edits are safe, export would be blocked", systemImage: "exclamationmark.triangle.fill")
                    .font(.caption2)
                    .foregroundStyle(.orange)
            }
        }
    }

    private func hasMissingSource(_ draft: Draft) -> Bool {
        draft.clips.contains { clip in
            guard let source = library.clips.first(where: { $0.id == clip.sourceClipID }) else {
                return true
            }
            if case .missing = library.availability[source.id] ?? .unknown {
                return true
            }
            return false
        }
    }
}

/// Formats seconds as m:ss.s for trim points and durations.
func timeString(_ seconds: Double) -> String {
    let minutes = Int(seconds) / 60
    let rest = seconds - Double(minutes * 60)
    return String(format: "%d:%04.1f", minutes, rest)
}
