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

import SwiftUI
import AudioPlaybackKit

/// View for editing existing alarms
struct EditAlarmView: View {
    
    // MARK: - Properties
    let viewModel: AlarmViewModel
    let alarm: Alarm
    @Environment(\.dismiss) private var dismiss
    
    @State private var alarmTime: Date
    @State private var selectedSoundName: String
    @State private var alarmLabel: String
    @State private var notificationMessage: String
    @State private var snoozeDuration: Int
    @State private var isVibrationEnabled: Bool
    @State private var isLightFlashEnabled: Bool
    @State private var volume: Float
    
    // MARK: - Initialization
    init(viewModel: AlarmViewModel, alarm: Alarm) {
        self.viewModel = viewModel
        self.alarm = alarm
        
        // Initialize state with current alarm values
        self._alarmTime = State(initialValue: alarm.time)
        self._selectedSoundName = State(initialValue: alarm.soundName)
        self._alarmLabel = State(initialValue: alarm.label)
        self._notificationMessage = State(initialValue: alarm.notificationMessage)
        self._snoozeDuration = State(initialValue: alarm.snoozeDuration)
        self._isVibrationEnabled = State(initialValue: alarm.isVibrationEnabled)
        self._isLightFlashEnabled = State(initialValue: alarm.isLightFlashEnabled)
        self._volume = State(initialValue: alarm.volume)
    }
    
    // MARK: - Body
    var body: some View {
        NavigationView {
            VStack(spacing: 0) {
                // Time picker section at top
                TimePickerSection(selectedTime: $alarmTime)
                TimeUntilAlarmSection(alarmTime: alarmTime)
                
                // List for settings below
                List {
                    // Label Section
                    NavigationLink(destination: LabelEditView(label: $alarmLabel)) {
                        HStack {
                            Image(systemName: "textformat")
                                .foregroundColor(AppAccent.primary)
                                .frame(width: 24)
                            Text("Label")
                            Spacer()
                            Text(alarmLabel)
                                .foregroundColor(.secondary)
                        }
                    }
                    
                    // Notification Message Section
                    NavigationLink(destination: NotificationMessageEditView(message: $notificationMessage)) {
                        HStack {
                            Image(systemName: "message")
                                .foregroundColor(AppAccent.primary)
                                .frame(width: 24)
                            Text("Message")
                            Spacer()
                            Text(notificationMessage)
                                .foregroundColor(.secondary)
                                .lineLimit(1)
                        }
                    }
                    
                    // Sound Section
                    NavigationLink(destination: SoundSelectionView(selectedSound: $selectedSoundName)) {
                        HStack {
                            Image(systemName: "music.note")
                                .foregroundColor(AppAccent.primary)
                                .frame(width: 24)
                            Text("Sound")
                            Spacer()
                            Text(getSoundDisplayName(selectedSoundName))
                                .foregroundColor(.secondary)
                        }
                    }
                    
                    // Snooze Section
                    NavigationLink(destination: SnoozeSelectionView(snoozeDuration: $snoozeDuration)) {
                        HStack {
                            Image(systemName: "clock.arrow.circlepath")
                                .foregroundColor(AppAccent.primary)
                                .frame(width: 24)
                            Text("Snooze")
                            Spacer()
                            Text("for \(snoozeDuration) min")
                                .foregroundColor(.secondary)
                        }
                    }
                }
                .listStyle(.insetGrouped)
            }
            .navigationTitle("Edit Alarm")
            .navigationBarTitleDisplayMode(.inline)
            .navigationBarBackButtonHidden(true)
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Button("Cancel") {
                        dismiss()
                    }
                    .foregroundColor(AppAccent.primary)
                }
                
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button("Save") {
                        Task {
                            let updatedAlarm = Alarm(
                                id: alarm.id, // Keep the same ID
                                time: alarmTime,
                                isEnabled: alarm.isEnabled, // Keep the same enabled state
                                soundName: selectedSoundName,
                                label: alarmLabel,
                                notificationMessage: notificationMessage,
                                snoozeDuration: snoozeDuration,
                                isVibrationEnabled: isVibrationEnabled,
                                isLightFlashEnabled: isLightFlashEnabled,
                                volume: volume
                            )
                            await viewModel.updateAlarm(updatedAlarm)
                            dismiss()
                        }
                    }
                    .foregroundColor(AppAccent.primary)
                    .fontWeight(.semibold)
                }
            }
        }
    }
    
    // MARK: - Helper Methods
    private func getSoundDisplayName(_ fileName: String) -> String {
        return AlarmSoundService.shared.getSoundDisplayName(fileName)
    }
}

// MARK: - Preview
#Preview {
    EditAlarmView(
        viewModel: AlarmViewModel(),
        alarm: Alarm(
            time: Date(),
            label: "Morning Alarm",
            notificationMessage: "Time to wake up!"
        )
    )
}
