import SwiftData
import SwiftUI

enum DeleteAfter: Int, CaseIterable {
    case oneDay = 1
    case oneWeek = 7
    case oneMonth = 30
    case oneYear = 365
    case never = 0

    var label: String {
        switch self {
        case .oneDay: "1 Day"
        case .oneWeek: "1 Week"
        case .oneMonth: "1 Month"
        case .oneYear: "1 Year"
        case .never: "Never"
        }
    }
}

struct SettingsView: View {
    @AppStorage("save_messages") private var saveMessages = true
    @AppStorage("save_debug_buffer") private var saveDebugBuffer = false
    @AppStorage("delete_after") private var deleteAfterRaw = DeleteAfter.oneMonth.rawValue
    @AppStorage("haptics_enabled") private var hapticsEnabled = true
    @AppStorage("haptics_messages") private var messageHaptics = true
    @AppStorage("haptics_status") private var statusHaptics = true
    @AppStorage("sounds_enabled") private var soundsEnabled = true
    @AppStorage("sounds_global") private var globalSound = true
    @AppStorage("sounds_map") private var mapSound = true
    @AppStorage("sounds_dm") private var dmSound = true
    @AppStorage("sounds_background_buffers") private var backgroundBufferSounds = true
    @AppStorage("announce_other_buffers") private var announceOtherBuffers = false
    @Environment(\.modelContext) private var modelContext
    @State private var showDeleteConfirmation = false

    private var deleteAfter: Binding<DeleteAfter> {
        Binding(
            get: { DeleteAfter(rawValue: deleteAfterRaw) ?? .oneMonth },
            set: { deleteAfterRaw = $0.rawValue }
        )
    }

    var body: some View {
        Form {
            Section {
                Toggle("Save Messages", isOn: $saveMessages)
                Toggle("Save Debug Buffer", isOn: $saveDebugBuffer)
                    .disabled(!saveMessages)
                Picker("Delete After", selection: deleteAfter) {
                    ForEach(DeleteAfter.allCases, id: \.self) { option in
                        Text(option.label).tag(option)
                    }
                }
                .disabled(!saveMessages)
                Button("Delete All Messages", role: .destructive) {
                    showDeleteConfirmation = true
                }
                .confirmationDialog(
                    "Delete Messages",
                    isPresented: $showDeleteConfirmation,
                    titleVisibility: .visible
                ) {
                    Button("Delete All Messages", role: .destructive) {
                        deleteAllMessages()
                    }
                } message: {
                    Text("Are you sure you want to delete all messages from all buffers?")
                }
            } header: {
                Text("Messages")
            } footer: {
                Text("Save Debug Buffer saves system and debug messages between sessions.")
            }

            Section {
                Toggle("Sounds", isOn: $soundsEnabled)
                Toggle("Global Chat", isOn: $globalSound)
                    .disabled(!soundsEnabled)
                Toggle("Map Chat", isOn: $mapSound)
                    .disabled(!soundsEnabled)
                Toggle("Direct Messages", isOn: $dmSound)
                    .disabled(!soundsEnabled)
                Toggle("Background Buffer Sounds", isOn: $backgroundBufferSounds)
                    .disabled(!soundsEnabled)
            } header: {
                Text("Sounds")
            } footer: {
                Text("Background Buffer Sounds plays sounds for messages in buffers you're not currently viewing.")
            }

            Section {
                Toggle("Haptics", isOn: $hapticsEnabled)
                Toggle("Message Haptics", isOn: $messageHaptics)
                    .disabled(!hapticsEnabled)
                Toggle("Status Haptics", isOn: $statusHaptics)
                    .disabled(!hapticsEnabled)
            } header: {
                Text("Haptics")
            } footer: {
                Text("Status Haptics provides feedback for system events such as connect and disconnect.")
            }

            Section {
                Toggle("Announce Background Messages", isOn: $announceOtherBuffers)
            } header: {
                Text("Accessibility")
            } footer: {
                Text("When on, VoiceOver announces new messages from buffers you're not currently viewing.")
            }

            Section {
                Link("Visit Website", destination: URL(string: "https://kpguild.games")!)
            }

            Section {
                Text("\(AppInfo.name) \(AppInfo.version) (\(AppInfo.build)) \(AppInfo.distribution.rawValue)")
                    .foregroundStyle(.secondary)
                    .frame(maxWidth: .infinity, alignment: .center)
            }
        }
        .navigationTitle("Settings")
        .onChange(of: saveMessages) {
            if !saveMessages {
                deleteAllMessages()
            }
        }
    }

    private func deleteAllMessages() {
        try? modelContext.delete(model: SavedMessage.self)
        try? modelContext.save()
    }
}
