//
//  AlarmRowView.swift
//  TheNoiseClock
//
//  Created by Matt Bruce on 9/7/25.
//

import SwiftUI
import Bedrock
import Foundation

/// Component for displaying individual alarm row
struct AlarmRowView: View {
    
    // MARK: - Properties
    let alarm: Alarm
    let onToggle: () -> Void
    let onEdit: () -> Void
    @AppStorage(ClockStyle.appStorageKey) private var clockStyleData: Data = Data()
    
    // MARK: - Body
    var body: some View {
        HStack {
            VStack(alignment: .leading, spacing: Design.Spacing.xSmall) {
                Text(alarm.formattedTime())
                    .font(.headline)
                    .foregroundColor(AppTextColors.primary)
                
                Text(alarm.label)
                    .font(.subheadline)
                    .foregroundColor(AppTextColors.secondary)
                
                Text("• \(AlarmSoundService.shared.getSoundDisplayName(alarm.soundName))")
                    .font(.caption)
                    .foregroundColor(AppTextColors.secondary)
                
                if alarm.isEnabled && !isKeepAwakeEnabled {
                    HStack(spacing: Design.Spacing.xSmall) {
                        Image(systemName: "exclamationmark.triangle.fill")
                            .font(.caption2)
                            .foregroundStyle(AppStatus.warning)
                        Text("Foreground only for full alarm sound")
                            .font(.caption2)
                            .foregroundStyle(AppTextColors.tertiary)
                    }
                }
            }
            
            Spacer()
            
            Toggle("", isOn: Binding(
                get: { alarm.isEnabled },
                set: { _ in onToggle() }
            ))
            .labelsHidden()
        }
        .contentShape(Rectangle())
        .onTapGesture {
            onEdit()
        }
    }
    
    private var isKeepAwakeEnabled: Bool {
        guard let decoded = try? JSONDecoder().decode(ClockStyle.self, from: clockStyleData) else {
            return ClockStyle().keepAwake
        }
        return decoded.keepAwake
    }
    
}

// MARK: - Preview
#Preview {
    List {
        AlarmRowView(
            alarm: Alarm(time: Date()),
            onToggle: {},
            onEdit: {}
        )
    }
}
