import SwiftUI

struct MethodPreferenceView: View {
    @State private var methods: Set<String> = ["间隔回忆", "费曼技巧"]
    let allMethods = ["间隔回忆", "费曼技巧", "AI 分析", "主动回忆"]
    @State private var saved = false
    @State private var isSaving = false

    var body: some View {
        ZStack {
            Color.zxBg0.ignoresSafeArea()
            ScrollView {
                VStack(spacing: 16) {
                    VStack(alignment: .leading, spacing: 10) {
                        Text("选择你偏好的学习方法").font(.system(size: 12, weight: .semibold)).foregroundColor(Color.zxF035)
                        ForEach(allMethods, id: \.self) { m in let sel = methods.contains(m)
                            Button { if sel { methods.remove(m) } else { methods.insert(m) } } label: {
                                HStack(spacing: 12) {
                                    Image(systemName: sel ? "checkmark.circle.fill" : "circle").font(.system(size: 20)).foregroundColor(sel ? Color.zxPurple : Color.zxF02)
                                    Text(m).font(.system(size: 15, weight: .semibold)).foregroundColor(Color.zxF0)
                                    Spacer()
                                }.padding(14).background(sel ? Color(hex: "#7C6EFA", opacity: 0.08) : Color.zxFill003).clipShape(RoundedRectangle(cornerRadius: 14))
                            }.foregroundColor(.primary)
                        }
                    }
                    Button {
                        Task {
                            isSaving = true
                            _ = try? await UserService.shared.updatePreferences(UpdatePreferencesRequest(
                                preferredMethods: Array(methods), defaultFocusMinutes: nil,
                                aiSuggestionLevel: nil, language: nil, appearance: nil,
                                notificationEnabled: nil
                            ))
                            saved = true
                            isSaving = false
                        }
                    } label: {
                        HStack(spacing: 8) {
                            if isSaving { ProgressView().tint(.white) }
                            Text(saved ? "已保存" : "保存").font(.system(size: 14, weight: .bold))
                        }
                        .foregroundColor(.white).frame(maxWidth: .infinity).frame(height: 52)
                        .background(isSaving ? AnyView(Color.gray) : AnyView(ZXGradient.ctaPurple))
                        .clipShape(RoundedRectangle(cornerRadius: 16))
                    }
                    .disabled(isSaving)
                }.padding(.horizontal, 20).padding(.top, 8).padding(.bottom, 80)
            }.scrollIndicators(.hidden)
        }.navigationBarTitleDisplayMode(.inline).animatedTabBarHide().toolbarBackground(.hidden, for: .navigationBar)
    }
}
