import SwiftUI
import SwiftData
import HealthKit
import UIKit

struct SettingsView: View {
    @Environment(\.modelContext) private var modelContext
    @Environment(AppSettings.self) private var appSettings
    @Query private var snapshots: [HealthSnapshot]
    @Query private var deviceProfiles: [DeviceProfile]
    @AppStorage("checkFrequencyHours") private var checkFrequencyHours: Int = 6
    @State private var showDeleteConfirm = false

    private var currentDeviceID: String {
        UIDevice.current.identifierForVendor?.uuidString ?? ""
    }

    private var currentDeviceProfile: DeviceProfile? {
        deviceProfiles.first { $0.deviceID == currentDeviceID }
    }

    var body: some View {
        NavigationStack {
            List {
                deviceSection
                monitoringSection
                typeSelectionSections
                dataSection
                aboutSection
            }
            .navigationTitle("Settings")
            .onAppear { ensureCurrentDeviceProfile() }
            .confirmationDialog(
                "Delete All Audit Data",
                isPresented: $showDeleteConfirm,
                titleVisibility: .visible
            ) {
                Button("Delete All Data", role: .destructive) { deleteAllData() }
                Button("Cancel", role: .cancel) { }
            } message: {
                Text("This permanently deletes all \(snapshots.count) snapshots. This action cannot be undone.")
            }
        }
    }

    // MARK: - Sections

    private var deviceSection: some View {
        Section("This Device") {
            if let profile = currentDeviceProfile {
                HStack {
                    Text("Name")
                    Spacer()
                    TextField("Device name", text: Binding(
                        get: { profile.name },
                        set: { profile.name = $0 }
                    ))
                    .multilineTextAlignment(.trailing)
                    .foregroundStyle(.secondary)
                }

                HStack {
                    Text("Color")
                    Spacer()
                    HStack(spacing: 10) {
                        ForEach(DeviceColor.allCases) { dc in
                            ZStack {
                                Circle()
                                    .fill(dc.color)
                                    .frame(width: 24, height: 24)
                                if profile.colorTag == dc.rawValue {
                                    Circle()
                                        .strokeBorder(.primary.opacity(0.75), lineWidth: 2.5)
                                        .frame(width: 24, height: 24)
                                }
                            }
                            .onTapGesture { profile.colorTag = dc.rawValue }
                            .accessibilityLabel(dc.rawValue.capitalized)
                            .accessibilityAddTraits(profile.colorTag == dc.rawValue ? .isSelected : [])
                        }
                    }
                }
            } else {
                Text("Loading…")
                    .foregroundStyle(.secondary)
            }
        }
    }

    private var monitoringSection: some View {
        Section("Monitoring") {
            Picker("Check Frequency", selection: $checkFrequencyHours) {
                Text("Every 2 hours").tag(2)
                Text("Every 6 hours").tag(6)
                Text("Every 12 hours").tag(12)
                Text("Every 24 hours").tag(24)
            }
        }
    }

    @ViewBuilder
    private var typeSelectionSections: some View {
        ForEach(TypeCategory.allCases, id: \.self) { category in
            Section(category.rawValue) {
                ForEach(HealthKitService.allTypes.filter { $0.category == category }) { type in
                    TypeToggleRow(type: type, appSettings: appSettings)
                }
            }
        }
    }

    private var dataSection: some View {
        Section("Data") {
            InfoRow(label: "Stored Snapshots") {
                Text("\(snapshots.count)")
                    .foregroundStyle(.secondary)
            }
            Button(role: .destructive) {
                showDeleteConfirm = true
            } label: {
                Label("Delete All Audit Data", systemImage: "trash")
            }
            .disabled(snapshots.isEmpty)
        }
    }

    private var aboutSection: some View {
        Section("About") {
            InfoRow(label: "Version") {
                Text(Bundle.main.appVersionString)
                    .foregroundStyle(.secondary)
            }
            InfoRow(label: "Purpose") {
                Text("Read-only HealthKit audit tool")
                    .foregroundStyle(.secondary)
            }
        }
    }

    // MARK: - Actions

    private func ensureCurrentDeviceProfile() {
        guard currentDeviceProfile == nil, !currentDeviceID.isEmpty else { return }
        modelContext.insert(DeviceProfile(deviceID: currentDeviceID))
    }

    private func deleteAllData() {
        for snapshot in snapshots { modelContext.delete(snapshot) }
        try? modelContext.save()
    }
}

// MARK: - Subviews

private struct TypeToggleRow: View {
    let type: MonitoredType
    let appSettings: AppSettings

    var body: some View {
        Toggle(isOn: Binding(
            get: { appSettings.isEnabled(type) },
            set: { _ in appSettings.toggle(type) }
        )) {
            Text(type.displayName)
        }
        .accessibilityLabel("\(type.displayName), \(appSettings.isEnabled(type) ? "enabled" : "disabled")")
    }
}

private struct InfoRow<Content: View>: View {
    let label: String
    @ViewBuilder let content: () -> Content
    var body: some View {
        HStack { Text(label); Spacer(); content() }
    }
}

private extension Bundle {
    var appVersionString: String {
        let version = infoDictionary?["CFBundleShortVersionString"] as? String ?? "–"
        let build   = infoDictionary?["CFBundleVersion"] as? String ?? "–"
        return "\(version) (\(build))"
    }
}

#Preview {
    SettingsView()
        .modelContainer(for: [HealthSnapshot.self, TypeCount.self, YearlyCount.self, DeviceProfile.self], inMemory: true)
        .environment(AppSettings())
}
