import SwiftUI

struct AlertsView: View {
    @State private var alerts: [AlertItem] = []
    @State private var status = ""
    @State private var isLoading = false

    var body: some View {
        NavigationStack {
            ScrollView {
                if alerts.isEmpty {
                    Text(status.isEmpty ? "No alerts." : status)
                        .foregroundStyle(ViewerTheme.muted)
                        .padding(.top, 40)
                } else {
                    LazyVStack(spacing: 10) {
                        ForEach(alerts) { alert in
                            Button {
                                Task { await markRead(alert) }
                            } label: {
                                AlertRow(alert: alert)
                            }
                            .buttonStyle(.plain)
                        }
                    }
                    .padding(20)
                }
            }
            .navigationTitle("Alerts")
            .scrollContentBackground(.hidden)
            .background(ViewerTheme.pageBackground.ignoresSafeArea())
            .toolbar {
                ToolbarItem(placement: .topBarTrailing) {
                    Button("Mark all read") {
                        Task { await markAllRead() }
                    }
                    .disabled(alerts.isEmpty)
                }
            }
            .refreshable { await load() }
            .task { await load() }
        }
    }

    private func load() async {
        guard !isLoading else { return }
        isLoading = true
        defer { isLoading = false }
        do {
            alerts = try await APIClient.shared.alerts()
            status = ""
        } catch {
            status = error.localizedDescription
        }
    }

    private func markRead(_ alert: AlertItem) async {
        guard !(alert.is_read ?? false) else { return }
        try? await APIClient.shared.markAlertRead(id: alert.id)
        await load()
    }

    private func markAllRead() async {
        try? await APIClient.shared.markAllAlertsRead()
        await load()
    }
}

struct AlertRow: View {
    let alert: AlertItem

    var title: String {
        switch alert.type {
        case "otp": return "OTP alert"
        case "large_payment": return "Large payment alert"
        case "sync_failed": return "Sync failure alert"
        default: return "Alert"
        }
    }

    var body: some View {
        ViewerCard {
            HStack(alignment: .top) {
                VStack(alignment: .leading, spacing: 4) {
                    Text(title).font(.headline).foregroundStyle(ViewerTheme.ink)
                    if let sender = alert.message?.sender {
                        Text("From \(sender)").font(.caption).foregroundStyle(ViewerTheme.muted)
                    }
                }
                Spacer()
                if !(alert.is_read ?? false) {
                    Circle().fill(.red).frame(width: 8, height: 8)
                }
            }
        }
    }
}
