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]
    @AppStorage("checkFrequencyHours") private var checkFrequencyHours: Int = 6
    @State private var showDeleteConfirm = false
    @State private var showRepairLegacyRecordsConfirm = false
    @State private var dataMaintenanceMessage: String?
    @State private var timeoutProfiles: [LocalMetricTimeoutProfile] = []
    @State private var currentDeviceProfile: LocalDeviceProfile?

    private var currentDeviceID: String {
        AppSettings.currentDeviceID
    }

    var body: some View {
        NavigationStack {
            List {
                deviceSection
                interfaceSection
                monitoringSection
                timeoutCalibrationSection
                typeSelectionSections
                dataSection
                aboutSection
            }
            .navigationTitle("Settings")
            .onAppear {
                loadCurrentDeviceProfile()
                loadTimeoutProfiles()
            }
            .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.")
            }
            .confirmationDialog(
                "Repair Legacy Records",
                isPresented: $showRepairLegacyRecordsConfirm,
                titleVisibility: .visible
            ) {
                Button("Delete Legacy Record Rows", role: .destructive) { repairLegacyRecordRows() }
                Button("Cancel", role: .cancel) { }
            } message: {
                Text("This removes old per-record SwiftData rows left by earlier builds. Compact record archives and snapshot counts are preserved.")
            }
        }
    }

    // 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: { newName in
                            updateCurrentDeviceProfile { profile in
                                profile.name = newName
                            }
                        }
                    ))
                    .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 {
                                updateCurrentDeviceProfile { profile in
                                    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)
            }
        }
    }

    private var interfaceSection: some View {
        Section("Interface") {
            Toggle("Simplified Detail Views", isOn: Binding(
                get: { appSettings.simplifiedUIModeEnabled },
                set: { appSettings.simplifiedUIModeEnabled = $0 }
            ))
        }
    }

    private var timeoutCalibrationSection: some View {
        Section("Timeout Calibration") {
            Toggle("Adaptive Timeouts", isOn: Binding(
                get: { appSettings.adaptiveTimeoutsEnabled },
                set: { appSettings.adaptiveTimeoutsEnabled = $0 }
            ))

            InfoRow(label: "Default Initial Timeout") {
                Text(formatDuration(LocalMetricTimeoutProfile.defaultInitialTimeout))
                    .foregroundStyle(.secondary)
            }

            InfoRow(label: "Maximum Timeout") {
                Text(formatDuration(LocalMetricTimeoutProfile.maximumTimeout))
                    .foregroundStyle(.secondary)
            }

            ForEach(timeoutProfiles) { profile in
                TimeoutProfileRow(
                    profile: profile,
                    onManualTimeoutChanged: { setManualTimeout(profile.metricIdentifier, value: $0) },
                    onSetManual: { setManualTimeout(profile.metricIdentifier, value: profile.effectiveTimeout) },
                    onAutomatic: { returnTimeoutProfileToAutomatic(profile.metricIdentifier) },
                    onReset: { resetTimeoutProfile(profile.metricIdentifier) }
                )
            }

            Button(role: .destructive) {
                resetAllTimeoutProfiles()
            } label: {
                Label("Reset All Learned Timeouts", systemImage: "arrow.counterclockwise")
            }
            .disabled(timeoutProfiles.isEmpty)
        }
    }

    @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)

            Button {
                showRepairLegacyRecordsConfirm = true
            } label: {
                Label("Repair Legacy Record Rows", systemImage: "wrench.and.screwdriver")
            }

            if let dataMaintenanceMessage {
                Text(dataMaintenanceMessage)
                    .font(.caption)
                    .foregroundStyle(.secondary)
            }
        }
    }

    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 loadCurrentDeviceProfile() {
        currentDeviceProfile = LocalDeviceProfileStore.profile(for: currentDeviceID)
        if let currentDeviceProfile {
            LocalDeviceProfileStore.save(currentDeviceProfile)
        }
    }

    private func updateCurrentDeviceProfile(_ mutate: (inout LocalDeviceProfile) -> Void) {
        var profile = currentDeviceProfile ?? LocalDeviceProfileStore.profile(for: currentDeviceID)
        mutate(&profile)
        currentDeviceProfile = profile
        LocalDeviceProfileStore.save(profile)
    }

    private func loadTimeoutProfiles() {
        timeoutProfiles = LocalMetricTimeoutProfileStore.allProfiles()
    }

    private func resetAllTimeoutProfiles() {
        LocalMetricTimeoutProfileStore.resetAll()
        loadTimeoutProfiles()
    }

    private func setManualTimeout(_ metricIdentifier: String, value: TimeInterval) {
        updateTimeoutProfile(metricIdentifier) { profile in
            profile.setManualTimeout(value)
        }
    }

    private func returnTimeoutProfileToAutomatic(_ metricIdentifier: String) {
        updateTimeoutProfile(metricIdentifier) { profile in
            profile.returnToAutomatic()
        }
    }

    private func resetTimeoutProfile(_ metricIdentifier: String) {
        updateTimeoutProfile(metricIdentifier) { profile in
            profile.resetLearning()
        }
    }

    private func updateTimeoutProfile(
        _ metricIdentifier: String,
        mutate: (inout LocalMetricTimeoutProfile) -> Void
    ) {
        guard let index = timeoutProfiles.firstIndex(where: { $0.metricIdentifier == metricIdentifier }) else {
            return
        }
        mutate(&timeoutProfiles[index])
        LocalMetricTimeoutProfileStore.save(timeoutProfiles[index])
        loadTimeoutProfiles()
    }

    private func deleteAllData() {
        do {
            try modelContext.delete(model: HealthRecord.self)
            try modelContext.delete(model: TypeDistributionBin.self)
            try modelContext.delete(model: YearlyCount.self)
            try modelContext.delete(model: TypeCount.self)
            try modelContext.delete(model: HealthSnapshot.self)
            try modelContext.save()
            dataMaintenanceMessage = "Audit data deleted."
        } catch {
            dataMaintenanceMessage = "Delete failed: \(error.localizedDescription)"
        }
    }

    private func repairLegacyRecordRows() {
        do {
            try modelContext.delete(model: HealthRecord.self)
            try modelContext.save()
            dataMaintenanceMessage = "Legacy record rows deleted."
        } catch {
            dataMaintenanceMessage = "Repair failed: \(error.localizedDescription)"
        }
    }
}

// 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 TimeoutProfileRow: View {
    let profile: LocalMetricTimeoutProfile
    let onManualTimeoutChanged: (TimeInterval) -> Void
    let onSetManual: () -> Void
    let onAutomatic: () -> Void
    let onReset: () -> Void

    var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            HStack(alignment: .firstTextBaseline) {
                Text(profile.displayName)
                    .font(.subheadline.weight(.semibold))
                Spacer()
                Text(formatDuration(profile.effectiveTimeout))
                    .font(.subheadline.weight(.semibold))
                    .foregroundStyle(.secondary)
            }

            HStack {
                Text(profile.timeoutMode.capitalized)
                Spacer()
                Text("Success \(profile.successCount)")
                Text("Timeouts \(profile.timeoutCount)")
            }
            .font(.caption)
            .foregroundStyle(.secondary)

            HStack {
                Text("Last success")
                Spacer()
                Text(profile.lastSuccessfulElapsed > 0 ? formatDuration(profile.lastSuccessfulElapsed) : "none")
            }
            .font(.caption)
            .foregroundStyle(.secondary)

            HStack {
                Text("Last timeout")
                Spacer()
                Text(profile.lastTimeoutElapsed > 0 ? formatDuration(profile.lastTimeoutElapsed) : "none")
            }
            .font(.caption)
            .foregroundStyle(.secondary)

            HStack {
                Text("p95 success")
                Spacer()
                Text(profile.p95SuccessfulElapsedIfAvailable.map(formatDuration) ?? "collecting")
            }
            .font(.caption)
            .foregroundStyle(.secondary)

            if profile.isManuallyOverridden {
                Stepper(
                    "Manual \(formatDuration(profile.manualTimeoutValue))",
                    value: Binding(
                        get: { profile.manualTimeoutValue },
                        set: onManualTimeoutChanged
                    ),
                    in: LocalMetricTimeoutProfile.defaultInitialTimeout...LocalMetricTimeoutProfile.maximumTimeout,
                    step: 5
                )
                .font(.caption)
            }

            HStack {
                Button("Set Manual") {
                    onSetManual()
                }
                .buttonStyle(.borderless)

                Button("Automatic") {
                    onAutomatic()
                }
                .buttonStyle(.borderless)
                .disabled(!profile.isManuallyOverridden)

                Spacer()

                Button("Reset", role: .destructive) {
                    onReset()
                }
                .buttonStyle(.borderless)
            }
            .font(.caption)
        }
        .padding(.vertical, 4)
    }
}

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))"
    }
}

private func formatDuration(_ seconds: TimeInterval) -> String {
    if seconds <= 0 { return "none" }
    if seconds < 60 { return String(format: "%.0fs", seconds) }
    return "\(Int(seconds) / 60)m \(Int(seconds) % 60)s"
}

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