//
// OpenRocky — Voice-first AI Agent
// https://github.com/openrocky
//
// Developed by everettjf with the assistance of Claude Code and Codex.
// Date: 2026-03-25
// Copyright (c) 2026 everettjf. All rights reserved.
//

import SwiftUI

struct OpenRockyProviderSettingsView: View {
    @ObservedObject var providerStore: OpenRockyProviderStore
    @ObservedObject var realtimeProviderStore: OpenRockyRealtimeProviderStore
    @ObservedObject var skillStore: OpenRockyBuiltInToolStore
    @ObservedObject var characterStore: OpenRockyCharacterStore
    @StateObject private var customSkillStore = OpenRockyCustomSkillStore.shared
    @ObservedObject private var healthService = OpenRockyProviderHealthService.shared
    @Environment(\.dismiss) private var dismiss

    var body: some View {
        NavigationStack {
            List {
                // General — session-wide preferences
                Section("General") {
                    NavigationLink {
                        OpenRockyPreferencesView()
                    } label: {
                        settingsRow(
                            icon: "slider.horizontal.3",
                            tint: .indigo,
                            title: "Preferences",
                            subtitle: "Voice session, transcript, haptics"
                        )
                    }
                }

                // Model: realtime voice entry-point + back-end chat agent
                Section {
                    NavigationLink {
                        OpenRockyRealtimeProviderInstanceListView(realtimeProviderStore: realtimeProviderStore)
                    } label: {
                        settingsRow(
                            icon: "bolt.circle.fill",
                            tint: OpenRockyPalette.secondary,
                            title: "Realtime Voice",
                            subtitle: voiceStatusSummary
                        )
                    }

                    NavigationLink {
                        OpenRockyProviderInstanceListView(providerStore: providerStore)
                    } label: {
                        settingsRow(
                            icon: "bubble.left.and.text.bubble.right.fill",
                            tint: OpenRockyPalette.accent,
                            title: "Chat",
                            subtitle: chatStatusSummary,
                            healthStatus: providerStore.activeInstance.map { healthService.status(for: $0.id) }
                        )
                    }
                } header: {
                    Text("Model")
                } footer: {
                    Text("Realtime Voice is the single voice entry-point. Chat drives text chat and is the back-end agent for complex voice tasks (delegate-task).")
                }

                // Personality & Skills: character, tools, skills, memory
                Section("Personality & Skills") {
                    NavigationLink {
                        OpenRockyCharacterSettingsView(characterStore: characterStore)
                    } label: {
                        settingsRow(
                            icon: "person.crop.circle.fill",
                            tint: .pink,
                            title: "Character",
                            subtitle: characterStore.activeCharacter.name
                        )
                    }

                    NavigationLink {
                        OpenRockyBuiltInToolsSettingsView(toolStore: skillStore)
                    } label: {
                        settingsRow(
                            icon: "wrench.and.screwdriver.fill",
                            tint: OpenRockyPalette.accent,
                            title: "Tools",
                            subtitle: "\(skillStore.tools.count) tools available"
                        )
                    }

                    NavigationLink {
                        OpenRockyCustomSkillsListView(skillStore: customSkillStore)
                    } label: {
                        settingsRow(
                            icon: "sparkles",
                            tint: OpenRockyPalette.success,
                            title: "Skills",
                            subtitle: customSkillsSummary
                        )
                    }

                    NavigationLink {
                        OpenRockyMemorySettingsView()
                    } label: {
                        settingsRow(
                            icon: "brain.head.profile.fill",
                            tint: OpenRockyPalette.warning,
                            title: "Memory",
                            subtitle: "Persistent key-value store"
                        )
                    }
                }

                // Integrations: system bridges and storage the AI reaches into
                Section("Integrations") {
                    NavigationLink {
                        OpenRockyFeaturesSettingsView(toolStore: skillStore)
                    } label: {
                        settingsRow(
                            icon: "star.circle.fill",
                            tint: .orange,
                            title: "Features",
                            subtitle: "Siri, Email & more"
                        )
                    }

                    NavigationLink {
                        OpenRockyWorkspaceFilesView(
                            rootURL: workspaceURL,
                            title: "Workspace"
                        )
                    } label: {
                        settingsRow(
                            icon: "folder.fill",
                            tint: .cyan,
                            title: "Workspace",
                            subtitle: "Files created by the assistant"
                        )
                    }

                    NavigationLink {
                        OpenRockyMountSettingsView()
                    } label: {
                        settingsRow(
                            icon: "externaldrive.fill.badge.icloud",
                            tint: .blue,
                            title: "External Folders",
                            subtitle: mountsSummary
                        )
                    }
                }

                // System: diagnostics, feedback, about
                Section("System") {
                    NavigationLink {
                        OpenRockyUsageSettingsView()
                    } label: {
                        settingsRow(
                            icon: "chart.bar.fill",
                            tint: .purple,
                            title: "Usage",
                            subtitle: usageSummary
                        )
                    }

                    NavigationLink {
                        OpenRockyFeedbackView()
                    } label: {
                        settingsRow(
                            icon: "exclamationmark.bubble.fill",
                            tint: .red,
                            title: "Feedback",
                            subtitle: "Report issues or suggestions"
                        )
                    }

                    NavigationLink {
                        OpenRockyAboutView(
                            providerStore: providerStore,
                            realtimeProviderStore: realtimeProviderStore
                        )
                    } label: {
                        settingsRow(
                            icon: "heart.fill",
                            tint: .pink,
                            title: "About",
                            subtitle: "Open source project & credits"
                        )
                    }

                    NavigationLink {
                        OpenRockyLogsView()
                    } label: {
                        settingsRow(
                            icon: "doc.text.fill",
                            tint: .gray,
                            title: "Logs",
                            subtitle: "View & share runtime logs"
                        )
                    }
                }
            }
            .navigationTitle("Settings")
            .navigationBarTitleDisplayMode(.inline)
            .onAppear {
                healthService.checkAll(
                    chatStore: providerStore,
                    realtimeStore: realtimeProviderStore
                )
            }
            .toolbar {
                ToolbarItem(placement: .topBarTrailing) {
                    Button {
                        dismiss()
                    } label: {
                        Image(systemName: "xmark.circle.fill")
                            .font(.system(size: 20))
                            .symbolRenderingMode(.hierarchical)
                            .foregroundStyle(.secondary)
                    }
                }
            }
        }
    }

    private var workspaceURL: URL {
        if let path = OpenRockyShellRuntime.shared.workspacePath {
            return URL(fileURLWithPath: path)
        }
        return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
            .appendingPathComponent("OpenRockyWorkspace")
    }

    private var chatStatusSummary: String {
        let config = providerStore.configuration
        if config.isConfigured {
            return "\(config.provider.displayName) · \(config.modelID)"
        }
        return "Not configured"
    }

    private var voiceStatusSummary: String {
        let config = realtimeProviderStore.configuration
        if config.isConfigured {
            return config.provider.displayName
        }
        return "Not configured"
    }

    private var usageSummary: String {
        let service = OpenRockyUsageService.shared
        let todayTokens = service.totalTokensToday
        let todayRequests = service.totalRequestsToday
        if todayTokens == 0 { return "Token usage & metrics" }
        return "Today: \(Self.formatTokens(todayTokens)) tokens, \(todayRequests) requests"
    }

    private static func formatTokens(_ count: Int) -> String {
        if count >= 1_000_000 { return String(format: "%.1fM", Double(count) / 1_000_000) }
        if count >= 1_000 { return String(format: "%.1fK", Double(count) / 1_000) }
        return "\(count)"
    }

    private var mountsSummary: String {
        let count = OpenRockyMountStore.shared.mounts.count
        if count == 0 { return "Mount iCloud folders for AI access" }
        return "\(count) folder(s) mounted"
    }

    private var customSkillsSummary: String {
        let count = customSkillStore.skills.count
        if count == 0 { return "Add or import custom skills" }
        let enabled = customSkillStore.skills.filter(\.isEnabled).count
        return "\(enabled) of \(count) enabled"
    }

    private func settingsRow(icon: String, tint: Color, title: String, subtitle: String, healthStatus: OpenRockyProviderHealthService.HealthStatus? = nil) -> some View {
        HStack(spacing: 12) {
            ZStack {
                RoundedRectangle(cornerRadius: 10, style: .continuous)
                    .fill(tint.opacity(0.14))
                    .frame(width: 40, height: 40)
                Image(systemName: icon)
                    .font(.system(size: 16, weight: .bold))
                    .foregroundStyle(tint)
            }
            VStack(alignment: .leading, spacing: 2) {
                Text(title)
                    .font(.system(size: 16, weight: .bold, design: .rounded))
                Text(subtitle)
                    .font(.system(size: 12, weight: .medium))
                    .foregroundStyle(.secondary)
            }
            Spacer()
            if let status = healthStatus {
                healthDot(status)
            }
        }
        .padding(.vertical, 4)
    }

    @ViewBuilder
    private func healthDot(_ status: OpenRockyProviderHealthService.HealthStatus) -> some View {
        switch status {
        case .unknown:
            EmptyView()
        case .checking:
            ProgressView()
                .controlSize(.mini)
        case .healthy:
            Circle()
                .fill(.green)
                .frame(width: 8, height: 8)
        case .unhealthy:
            Circle()
                .fill(.red)
                .frame(width: 8, height: 8)
        }
    }
}
