import SwiftUI
internal import CoreData

struct HomeView: View {
    @Environment(\.managedObjectContext) private var viewContext
    @StateObject private var viewModel: HomeViewModel
    @State private var showingAddTicket = false
    @State private var selectedTicket: LotteryTicket?
    
    private var ticketsUpdatedPublisher: NotificationCenter.Publisher {
        NotificationCenter.default.publisher(for: .ticketsUpdated)
    }
    
    init() {
        // 创建 HomeViewModel 实例
        _viewModel = StateObject(
            wrappedValue: HomeViewModel(context: PersistenceController.shared.container.viewContext)
        )
    }
    
    var body: some View {
        NavigationStack {
            VStack(spacing: 0) {
                // 顶部统计卡片
                StatsCard(
                    totalSpent: viewModel.totalSpent,
                    totalProfit: viewModel.totalProfit,
                    totalTickets: viewModel.totalTickets,
                    winningTickets: viewModel.winningTickets,
                    pendingTickets: viewModel.pendingTickets
                )
                .padding(.top)
                
                // 记录列表或空状态
                if viewModel.totalTickets > 0 {
                    ticketList
                        .navigationDestination(item: $selectedTicket) { ticket in
                            TicketDetailView(ticket: ticket)
                        }
                } else {
                    EmptyStateView(onAddTapped: {
                        // 触发添加按钮动作
                        showingAddTicket = true
                    })
                    .padding(.top, 80)
                }
                
            }
            .navigationTitle("彩票记录")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button(action: { showingAddTicket = true }) {
                        Image(systemName: "plus.circle.fill")
                            .font(.system(size: 22))
                            .foregroundColor(.blue)
                    }
                }
                
                ToolbarItem(placement: .navigationBarLeading) {
                    Button(action: { viewModel.refreshData() }) {
                        Image(systemName: "arrow.clockwise")
                            .foregroundColor(.blue)
                    }
                }
            }
            .sheet(isPresented: $showingAddTicket) {
                AddTicketView()
                    .environment(\.managedObjectContext, viewContext)
            }
            .onAppear {
                viewModel.refreshData()
            }
            // 监听通知，自动刷新
            .onReceive(ticketsUpdatedPublisher) { notification in
                // 检查是否是清空操作
                if let userInfo = notification.userInfo,
                   let isClearOperation = userInfo["isClearOperation"] as? Bool,
                   isClearOperation {
                    print("🔄 收到清空数据通知，强制刷新首页")
                    viewModel.refreshData()
                    
                    // 如果是清空操作，还可以添加额外处理
                    // 比如：显示提示、动画等
                } else {
                    print("🔄 收到数据更新通知，刷新首页")
                    viewModel.refreshData()
                }
            }
        }
    }
    
    // 记录列表
    private var ticketList: some View {
        List {
            ForEach(viewModel.sortedDates, id: \.self) { date in
                Section {
                    ForEach(viewModel.ticketsForDate(date), id: \.id) { ticket in
                        TicketRow(ticket: ticket)
                            .contentShape(Rectangle()) // 让整个区域可点击
                            .onTapGesture {
                                selectedTicket = ticket
                            }
                            .swipeActions(edge: .trailing) {
                                Button(role: .destructive) {
                                    deleteTicket(ticket)
                                } label: {
                                    Label("删除", systemImage: "trash")
                                }
                            }
                    }
                } header: {
                    Text(viewModel.formattedDate(date))
                        .font(.subheadline)
                        .fontWeight(.semibold)
                        .foregroundColor(.secondary)
                        .textCase(nil)
                }
            }
        }
        .listStyle(.plain)
        .refreshable {
            viewModel.refreshData()
        }
        .padding(.top, 10)
    }
    
    // 删除记录
    private func deleteTicket(_ ticket: LotteryTicket) {
        viewContext.delete(ticket)
        
        do {
            try viewContext.save()
            viewModel.refreshData()
            print("✅ 删除成功")
            
            // 发送数据更新通知
            NotificationCenter.default.post(name: .ticketsUpdated, object: nil)
        } catch {
            print("❌ 删除失败: \(error)")
        }
    }
}

// 预览
struct HomeView_Previews: PreviewProvider {
    static var previews: some View {
        let context = PersistenceController.preview.container.viewContext
        
        // 添加预览数据
        for i in 1...8 {
            let ticket = LotteryTicket(context: context)
            ticket.id = UUID()
            ticket.type = i % 2 == 0 ? "双色球" : "大乐透"
            ticket.numbers = "测试号码 \(i)"
            ticket.betCount = Int16(i % 3 + 1)
            ticket.amount = Float(ticket.betCount) * 2.0
            ticket.date = Date().addingTimeInterval(Double(-i) * 86400)
            ticket.drawDate = Date().addingTimeInterval(Double(i) * 86400)
            ticket.status = i % 3 == 0 ? "待开奖" : (i % 3 == 2 ? "已中奖" : "未中奖")
            ticket.prizeAmount = ticket.status == "已中奖" ? ticket.amount * 5 : 0
        }
        
        return HomeView()
            .environment(\.managedObjectContext, context)
    }
}
