import SwiftUI
import AudioCore

struct ExportSheet: View {
    @Bindable var model: ProjectModel
    @Environment(\.dismiss) private var dismiss

    @State private var format: Mixdown.Format = .m4a
    @State private var includeTones = true
    @State private var isExporting = false
    @State private var exportedURL: URL?
    @State private var exportError: String?

    var body: some View {
        NavigationStack {
            Form {
                Section {
                    Picker("Format", selection: $format) {
                        Text("M4A (AAC)").tag(Mixdown.Format.m4a)
                        Text("WAV").tag(Mixdown.Format.wav)
                    }
                    Toggle("Include tones for unrecorded parts", isOn: $includeTones)
                } footer: {
                    let recorded = model.score.parts.map(\.name).filter { model.hasActiveTake($0) }
                    if recorded.isEmpty {
                        Text("No parts recorded yet — the export will be all guide tones.")
                    } else {
                        Text("Recorded: \(recorded.joined(separator: ", "))")
                    }
                }

                Section {
                    if let url = exportedURL {
                        ShareLink(item: url) {
                            Label("Share \(url.lastPathComponent)", systemImage: "square.and.arrow.up")
                        }
                    } else {
                        Button {
                            export()
                        } label: {
                            if isExporting {
                                HStack {
                                    ProgressView()
                                    Text("Rendering…")
                                }
                            } else {
                                Label("Render Mix", systemImage: "waveform.badge.plus")
                            }
                        }
                        .disabled(isExporting)
                    }
                }

                if let exportError {
                    Section {
                        Text(exportError).foregroundStyle(.red)
                    }
                }
            }
            .navigationTitle("Export Mix")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .topBarTrailing) {
                    Button("Done") { dismiss() }
                }
            }
            .onChange(of: format) { exportedURL = nil }
            .onChange(of: includeTones) { exportedURL = nil }
        }
    }

    private func export() {
        isExporting = true
        exportError = nil
        let score = model.score
        let title = score.title
        let volumes = model.volumes
        let options = Mixdown.Options(
            includeTonesForUnrecordedParts: includeTones,
            format: format,
            sampleRate: 48000,
            gains: volumes
        )
        do {
            // Take loading is quick file I/O; the heavy render goes off-main.
            let (takes, _) = try model.store.loadActiveTakes(
                engineRate: options.sampleRate,
                tempoMultiplier: model.tempoMultiplier
            )
            Task.detached(priority: .userInitiated) {
                do {
                    let url = try Mixdown.export(
                        score: score, takes: takes, options: options, suggestedName: title
                    )
                    await MainActor.run {
                        exportedURL = url
                        isExporting = false
                    }
                } catch {
                    await MainActor.run {
                        exportError = "Export failed: \(error.localizedDescription)"
                        isExporting = false
                    }
                }
            }
        } catch {
            exportError = "Export failed: \(error.localizedDescription)"
            isExporting = false
        }
    }
}
