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

import SwiftUI
import Bedrock

/// Main alarm management view
struct AlarmView: View {
    
    // MARK: - Properties
    @State private var viewModel = AlarmViewModel()
    @State private var showAddAlarm = false
    @State private var selectedAlarmForEdit: Alarm?
    
    // MARK: - Body
    var body: some View {
        Group {
            if viewModel.alarms.isEmpty {
                EmptyAlarmsView {
                    showAddAlarm = true
                }
                .contentShape(Rectangle())
                .onTapGesture {
                    showAddAlarm = true
                }
                .frame(maxWidth: Design.Size.maxContentWidthPortrait)
                .frame(maxWidth: .infinity, alignment: .center)
            } else {
                List {
                    ForEach(viewModel.alarms) { alarm in
                        AlarmRowView(
                            alarm: alarm,
                            onToggle: { 
                                Task {
                                    await viewModel.toggleAlarm(id: alarm.id)
                                }
                            },
                            onEdit: { 
                                selectedAlarmForEdit = alarm
                            }
                        )
                    }
                    .onDelete(perform: deleteAlarm)
                }
                .frame(maxWidth: Design.Size.maxContentWidthPortrait)
                .frame(maxWidth: .infinity, alignment: .center)
            }
        }
        .navigationTitle("Alarms")
        .toolbar {
            ToolbarItem(placement: .navigationBarTrailing) {
                Button {
                    showAddAlarm = true
                } label: {
                    Image(systemName: "plus")
                        .font(.title2)
                }
            }
        }
        .onAppear {
            Task {
                await viewModel.requestNotificationPermissions()
            }
        }
        .sheet(isPresented: $showAddAlarm) {
            AddAlarmView(
                viewModel: viewModel,
                isPresented: $showAddAlarm
            )
        }
        .sheet(item: $selectedAlarmForEdit) { alarm in
            EditAlarmView(
                viewModel: viewModel,
                alarm: alarm
            )
        }
    }
    
    // MARK: - Private Methods
    private func deleteAlarm(at offsets: IndexSet) {
        Task {
            for index in offsets {
                let alarm = viewModel.alarms[index]
                await viewModel.deleteAlarm(id: alarm.id)
            }
        }
    }
}

// MARK: - Preview
#Preview {
    NavigationStack {
        AlarmView()
    }
}
