import SwiftUI

struct SettingsView: View {
    @Environment(\.openWindow) private var openWindow
    @Environment(SceneStore.self) private var sceneStore
    @State private var systemPrompt: String = Preferences.systemPrompt
    @State private var apiPort: String = String(Preferences.apiPort)
    @State private var apiAutoStart: Bool = Preferences.apiAutoStart
    @State private var idleUnloadMinutes: String = String(Preferences.idleUnloadMinutes)
    @State private var defaultModelId: String = Preferences.defaultModelId ?? ModelConfig.default.id
    @State private var enableThinking: Bool = Preferences.enableThinking

    var body: some View {
        Form {
            Section("Startup") {
                Picker("Default model", selection: $defaultModelId) {
                    ForEach(ModelConfig.availableModels) { model in
                        Text(model.displayName).tag(model.id)
                    }
                }
                .onChange(of: defaultModelId) {
                    Preferences.defaultModelId = defaultModelId
                }

                Text("The model to load automatically when the app starts.")
                    .font(.caption)
                    .foregroundStyle(.secondary)
            }

            Section("Generation") {
                Toggle("Enable thinking mode", isOn: $enableThinking)
                    .onChange(of: enableThinking) {
                        Preferences.enableThinking = enableThinking
                    }

                Text("When enabled, models like Qwen3.5 reason internally before responding. Produces better answers but slower. Takes effect on the next conversation.")
                    .font(.caption)
                    .foregroundStyle(.secondary)
            }

            Section("System Prompt") {
                TextEditor(text: $systemPrompt)
                    .font(.body.monospaced())
                    .frame(minHeight: 80)
                    .onChange(of: systemPrompt) {
                        Preferences.systemPrompt = systemPrompt
                    }

                Text("Applied to new conversations. Leave empty for no system prompt.")
                    .font(.caption)
                    .foregroundStyle(.secondary)
            }

            Section("Scenes") {
                Button("Manage Scenes…") {
                    openWindow(id: SceneManagementWindow.windowID)
                }

                Text("Create reusable roleplay or task presets with a dedicated model, extra system prompt, and an auto-sent opening message.")
                    .font(.caption)
                    .foregroundStyle(.secondary)

                if sceneStore.scenes.isEmpty {
                    Text("No saved scenes yet.")
                        .font(.caption)
                        .foregroundStyle(.secondary)
                } else {
                    Text("Saved scenes: \(sceneStore.scenes.count)")
                        .font(.caption)
                        .foregroundStyle(.secondary)
                }
            }

            Section("API Server") {
                HStack {
                    Text("Port")
                    TextField("1234", text: $apiPort)
                        .frame(width: 80)
                        .onChange(of: apiPort) {
                            if let port = Int(apiPort), port > 0, port < 65536 {
                                Preferences.apiPort = port
                            }
                        }
                }

                Toggle("Start API server automatically", isOn: $apiAutoStart)
                    .onChange(of: apiAutoStart) {
                        Preferences.apiAutoStart = apiAutoStart
                    }
            }

            Section("Memory") {
                HStack {
                    Text("Unload model after idle")
                    TextField("3", text: $idleUnloadMinutes)
                        .frame(width: 50)
                        .onChange(of: idleUnloadMinutes) {
                            if let mins = Int(idleUnloadMinutes), mins > 0 {
                                Preferences.idleUnloadMinutes = mins
                            }
                        }
                    Text("minutes")
                        .foregroundStyle(.secondary)
                }

                Text("The model is automatically unloaded to free memory after being idle, and reloaded on the next request.")
                    .font(.caption)
                    .foregroundStyle(.secondary)
            }
        }
        .formStyle(.grouped)
        .frame(width: 450, height: 550)
    }
}
