import SwiftUI

struct ShareCsvSheet: View {

    @Binding var isPresented: Bool

    @State
    private var isCreatingFile = false

    @State var url: URL?

    @State var error: String?

    @EnvironmentObject
    private var storage: PersistentStorage

    let measurements: [TemperatureMeasurement]

    var body: some View {
        VStack {
            Text("Export")
                .font(.title)
            Text("Create a CSV file of all measurements for the day")
            if isCreatingFile {
                ProgressView()
                Text("Creating file...")
            }
            if let error {
                Text(error)
                    .foregroundStyle(.red)
            }
            Spacer()
            Button("Create file", action: createFile)
                .disabled(isCreatingFile)
                .padding()
            if let url {
                ShareLink(item: url) {
                    Label("Share file", systemImage: "square.and.arrow.up")
                }
                .padding()
                Button("Delete file", action: deleteFile)
                    .padding()
            }
            Button("Dismiss", action: { isPresented = false })
        }
        .padding()
    }

    private func createFile() {
        guard !isCreatingFile else {
            return
        }
        isCreatingFile = true
        DispatchQueue.main.async {
            do {
                let url = FileManager.default.temporaryDirectory.appendingPathComponent("export.csv")
                let converter = CsvConverter()
                let content = converter.convert(measurements: measurements)
                try content.write(to: url, atomically: true, encoding: .utf8)
                DispatchQueue.main.async {
                    self.url = url
                    self.error = nil
                    self.isCreatingFile = false
                }
            } catch {
                DispatchQueue.main.async {
                    self.error = "Failed to save file: \(error.localizedDescription)"
                    self.isCreatingFile = false
                }
            }
        }
    }

    private func deleteFile() {
        guard let url else {
            return
        }
        do {
            try FileManager.default.removeItem(at: url)
            self.error = nil
            self.url = nil
        } catch {
            self.error = "Failed to delete archive: \(error.localizedDescription)"
        }
    }
}

#Preview {
    ShareCsvSheet(isPresented: .constant(true),
                  measurements: [])
}
