import SwiftUI

struct ExportSheet: View {

    @Binding var isPresented: Bool

    @State
    private var isCreatingArchive = false

    @State var url: URL?

    @State var error: String?

    @EnvironmentObject
    private var storage: PersistentStorage

    var body: some View {
        VStack {
            Text("Export")
                .font(.title)
            Text("Create a zip file of all stored data and share it.")
            if isCreatingArchive {
                ProgressView()
                Text("Creating archive...")
            }
            if let error {
                Text(error)
                    .foregroundStyle(.red)
            }
            Spacer()
            Button("Create archive", action: createArchive)
                .disabled(isCreatingArchive)
                .padding()
            if let url {
                ShareLink(item: url) {
                    Label("Share archive", systemImage: "square.and.arrow.up")
                }
                .padding()
                Button("Delete archive", action: deleteArchive)
                    .padding()
            }
        }
        .padding()
    }

    private func createArchive() {
        guard !isCreatingArchive else {
            return
        }
        isCreatingArchive = true
        DispatchQueue.main.async {
            do {
                let url = try storage.createZip()
                DispatchQueue.main.async {
                    self.url = url
                    self.error = nil
                    self.isCreatingArchive = false
                }
            } catch {
                DispatchQueue.main.async {
                    self.error = "Failed to create archive: \(error.localizedDescription)"
                    self.isCreatingArchive = false
                }
            }
        }
    }

    private func deleteArchive() {
        do {
            try storage.removeZipArchive()
            self.error = nil
            self.url = nil
        } catch {
            self.error = "Failed to delete archive: \(error.localizedDescription)"
        }
    }
}

#Preview {
    ExportSheet(isPresented: .constant(true))
}
