import SwiftUI
import SwiftData
import SFSafeSymbols
import CryptoKit

struct ContentView: View {

    @Binding
    var didLaunchFromComplication: Bool

    @ObservedObject
    var coordinator: RequestCoordinator
    
    init(coordinator: RequestCoordinator, didLaunchFromComplication: Binding<Bool>) {
        self._didLaunchFromComplication = didLaunchFromComplication
        self.coordinator = coordinator
    }

    var buttonBackground: Color {
        .white.opacity(0.2)
    }

    var buttonColor: Color {
        .white
    }
    
    var body: some View {
        HStack {
            Spacer()
            VStack(alignment: .center) {
                Image(systemSymbol: .lock)
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .fontWeight(.ultraLight)
                    .padding()
                    .onTapGesture(perform: coordinator.startUnlock)
                if coordinator.isPerformingRequest {
                    ProgressView()
                        .progressViewStyle(CircularProgressViewStyle())
                        .frame(width: 20, height: 20)
                } else {
                    Text("Unlock")
                        .font(.subheadline)
                }
            }
            Spacer()
        }
        .background(coordinator.state.color)
        .animation(.easeInOut, value: coordinator.state.color)
        .onChange(of: didLaunchFromComplication) { _, launched in
            guard launched else {
                return
            }
            didLaunchFromComplication = false
            coordinator.startUnlock()
        }
    }
}

#Preview {
    do {
        let config = ModelConfiguration(isStoredInMemoryOnly: true)
        let container = try ModelContainer(for: HistoryItem.self, configurations: config)
        
        let item = HistoryItem.mock
        container.mainContext.insert(item)
        try container.mainContext.save()
        let coordinator = RequestCoordinator(modelContext: container.mainContext)
        return ContentView(coordinator: coordinator, didLaunchFromComplication: .constant(false))
            .modelContainer(container)
    } catch {
        fatalError("Failed to create model container.")
    }
}

