import SwiftUI
import SFSafeSymbols

private let df: DateFormatter = {
    let df = DateFormatter()
    df.dateStyle = .short
    df.timeStyle = .medium
    return df
}()

private let dateFormatter: DateFormatter = {
    let df = DateFormatter()
    df.dateStyle = .medium
    df.timeStyle = .none
    return df
}()

struct DayView: View {

    let dateIndex: Int

    @EnvironmentObject
    var storage: PersistentStorage

    @State
    private var showShareSheet = false

    private let title: String

    init(dateIndex: Int) {
        self.dateIndex = dateIndex
        self.title = Date(dateIndex: dateIndex)
            .formatted(date: .abbreviated, time: .omitted)
    }

    var entries: [TemperatureMeasurement] {
        storage.loadMeasurements(for: dateIndex)
    }

    var body: some View {
        VStack {
            TemperatureDayOverview(points: entries)
            List(entries) { entry in
                HStack {
                    Text(entry.date.formatted(date: .omitted, time: .standard))
                    Spacer()
                    Text(entry.displayText)
                }
            }
        }
        .navigationTitle(title)
        .navigationBarTitleDisplayMode(.large)
        .toolbar {
            ToolbarItem {
                Button(action: { showShareSheet = true }) {
                    Label("Export", systemSymbol: .arrowUpDoc)
                }
            }
        }
        .sheet(isPresented: $showShareSheet) {
            ShareCsvSheet(isPresented: $showShareSheet,
                          measurements: entries)
        }
    }
}

struct DayView_Previews: PreviewProvider {
    static var previews: some View {
        DayView(dateIndex: Date.now.dateIndex)
            .environmentObject(PersistentStorage.mock)
    }
}
