import SwiftUI
internal import CoreData

struct SettingsView: View {
    @Environment(\.managedObjectContext) private var viewContext
    @EnvironmentObject private var appState: AppState
    
    @AppStorage("enableNotifications") private var enableNotifications = true
    @AppStorage("autoCheckDraw") private var autoCheckDraw = true
    @AppStorage("currencySymbol") private var currencySymbol = "¥"
    
    @State private var showingClearAlert = false
    @State private var showingClearSuccess = false
    @State private var showingClearError = false
    @State private var clearErrorMessage = ""
    @State private var isClearing = false
    
    // 添加开发者选项的导航状态
//    @State private var showingDeveloperView = false
    
    var body: some View {
        NavigationView {
            List {
                // 通知设置
                Section("通知设置") {
                    Toggle("开启通知提醒", isOn: $enableNotifications)
                    
                    if enableNotifications {
                        Toggle("启动时检查开奖", isOn: $autoCheckDraw)
                        
                        Button("测试通知") {
                            testNotification()
                        }
                        .foregroundColor(.blue)
                    }
                }
                
                // 显示设置
                Section("显示设置") {
                    Picker("货币符号", selection: $currencySymbol) {
                        Text("¥").tag("¥")
                        Text("$").tag("$")
                        Text("€").tag("€")
                        Text("£").tag("£")
                    }
                }
                
                // 数据管理
                Section("数据管理") {
                    Button("导出数据") {
                        exportData()
                    }
                    .foregroundColor(.blue)
                    
                    Button("备份数据") {
                        backupData()
                    }
                    .foregroundColor(.blue)
                    
                    if isClearing {
                        HStack {
                            ProgressView()
                                .scaleEffect(0.8)
                            Text("正在清空数据...")
                                .foregroundColor(.secondary)
                        }
                    } else {
                        Button("清空所有数据") {
                            showingClearAlert = true
                        }
                        .foregroundColor(.red)
                    }
                }
                
                // 关于
                Section("关于") {
                    HStack {
                        Text("版本")
                        Spacer()
                        Text("1.0.0")
                            .foregroundColor(.secondary)
                    }
                    
                    Button("检查更新") {
                        checkForUpdates()
                    }
                    .foregroundColor(.blue)
                    
                    Button("用户协议") {
                        // 显示用户协议
                    }
                    .foregroundColor(.blue)
                    
                    Button("隐私政策") {
                        // 显示隐私政策
                    }
                    .foregroundColor(.blue)
                }
                
                // 开发者选项
                Section {
                    NavigationLink("开发者选项") {
                        DeveloperView()
                    }
                    .foregroundColor(.blue)
                }
            }
            .navigationTitle("设置")
            .navigationBarTitleDisplayMode(.inline)
            .alert("清空数据", isPresented: $showingClearAlert) {
                Button("取消", role: .cancel) { }
                Button("清空", role: .destructive) {
                    clearAllData()
                }
            } message: {
                Text("这将删除所有彩票记录，此操作不可撤销。确定要继续吗？")
            }
            .alert("清空成功", isPresented: $showingClearSuccess) {
                Button("确定", role: .cancel) { }
            } message: {
                Text("所有数据已成功清空")
            }
            .alert("清空失败", isPresented: $showingClearError) {
                Button("确定", role: .cancel) { }
            } message: {
                Text(clearErrorMessage)
            }
        }}
    
    // MARK: - 方法
    
    private func testNotification() {
        print("测试通知功能")
        // 这里可以添加测试通知的代码
    }
    
    private func exportData() {
        print("导出数据功能")
    }
    
    private func backupData() {
        print("数据备份功能")
    }
    
    // 清空所有数据（可靠版本）
    private func clearAllData() {
        isClearing = true
        
        // 在后台线程执行删除操作
        DispatchQueue.global(qos: .userInitiated).async {
            let fetchRequest: NSFetchRequest<NSFetchRequestResult> = LotteryTicket.fetchRequest()
            
            do {
                // 先获取所有记录
                if let tickets = try? self.viewContext.fetch(fetchRequest) as? [LotteryTicket] {
                    print("找到 \(tickets.count) 条记录需要删除")
                    
                    // 逐一删除
                    for ticket in tickets {
                        self.viewContext.delete(ticket)
                    }
                    
                    // 保存更改
                    if self.viewContext.hasChanges {
                        try self.viewContext.save()
                        print("✅ 保存删除操作")
                    }
                    
                    // 重置上下文
                    self.viewContext.reset()
                }
                
                DispatchQueue.main.async {
                    self.isClearing = false
                    self.showingClearSuccess = true
                    
                    // 发送数据更新通知，标记为清空操作
                    NotificationCenter.default.post(
                        name: .ticketsUpdated,
                        object: nil,
                        userInfo: ["isClearOperation": true]  // 添加标识
                    )
                    
                    // 可选：发送应用重置通知
                    NotificationCenter.default.post(name: .appReset, object: nil)
                    
                    print("✅ 所有数据已成功清空，已发送清空通知")
                }
            } catch {
                DispatchQueue.main.async {
                    self.isClearing = false
                    self.clearErrorMessage = "清空失败: \(error.localizedDescription)"
                    self.showingClearError = true
                    
                    print("❌ 清空数据失败: \(error)")
                }
            }
        }
    }
    
    private func checkForUpdates() {
        print("检查更新")
    }
}

// 预览
struct SettingsView_Previews: PreviewProvider {
    static var previews: some View {
        NavigationView {
            SettingsView()
        }
    }
}
