import SwiftUI
import Charts
internal import CoreData

struct StatisticsView: View {
    @Environment(\.managedObjectContext) private var context
    @StateObject private var statsService: StatisticsService
    
    @State private var selectedTimeRange = 30
    @State private var showingTypeDetail = false
    
    private let timeRanges = [7, 30, 90, 365]
    
    init() {
        _statsService = StateObject(
            wrappedValue: StatisticsService(context: PersistenceController.shared.container.viewContext)
        )
    }
    
    var body: some View {
        ScrollView {
            if statsService.isLoading {
                // 显示加载指示器
                VStack {
                    Spacer()
                    ProgressView()
                        .scaleEffect(1.2)
                    Text("加载统计数据中...")
                        .font(.headline)
                        .foregroundColor(.secondary)
                        .padding(.top)
                    Spacer()
                }
                .frame(height: 300)
            } else {
                VStack(spacing: 20) {
                    // 月度对比卡片
                    monthlyComparisonCard
                    
                    // 类型分布
                    typeDistributionCard
                    
                    // 盈亏趋势图
                    profitTrendCard
                    
                    // 统计数据总结
                    statsSummaryCard
                }
                .padding()
            }
        }
        .navigationTitle("数据统计")
        .navigationBarTitleDisplayMode(.inline)
        .task {
            // 使用 task 进行异步加载
            await statsService.loadAllStatistics()
        }
        .refreshable {
            // 下拉刷新
            await statsService.loadAllStatistics()
        }
        // StatisticsService 内部已经处理通知，这里不需要重复处理
        // 但如果需要 UI 响应，可以添加：
        .onReceive(NotificationCenter.default.publisher(for: .ticketsUpdated)) { notification in
            // 检查是否是清空操作
            if let userInfo = notification.userInfo,
               let isClearOperation = userInfo["isClearOperation"] as? Bool,
               isClearOperation {
                print("📊 统计页面：收到清空通知，显示空状态")
                // 这里不需要做额外处理，StatisticsService 已经处理了
            }
        }
    }
    
    // 月度对比卡片
    private var monthlyComparisonCard: some View {
        VStack(alignment: .leading, spacing: 16) {
            HStack {
                Text("月度对比")
                    .font(.headline)
                
                Spacer()
                
                Text("本月 vs 上月")
                    .font(.caption)
                    .foregroundColor(.secondary)
            }
            
            HStack(spacing: 20) {
                StatItem(
                    title: "本月投入",
                    value: Formatters.formatCurrency(statsService.monthlyStats.currentMonth.totalSpent),
                    color: .blue
                )
                
                StatItem(
                    title: "本月盈亏",
                    value: Formatters.formatCurrency(statsService.monthlyStats.currentMonth.totalProfit),
                    color: statsService.monthlyStats.currentMonth.totalProfit >= 0 ? .green : .red
                )
                
                StatItem(
                    title: "变化率",
                    value: "\(statsService.monthlyStats.profitChange, default: "%.1f")%",
                    color: statsService.monthlyStats.profitChange >= 0 ? .green : .red
                )
            }
        }
        .padding()
        .background(Color(.systemBackground))
        .cornerRadius(12)
        .shadow(color: .black.opacity(0.05), radius: 5)
    }
    
    // 类型分布卡片
    private var typeDistributionCard: some View {
        VStack(alignment: .leading, spacing: 16) {
            HStack {
                Text("类型分布")
                    .font(.headline)
                
                Spacer()
                
                Button("详情") {
                    showingTypeDetail = true
                }
                .font(.caption)
                .foregroundColor(.blue)
            }
            
            if statsService.typeDistribution.isEmpty {
                emptyStateView(title: "暂无类型分布数据")
            } else {
                Chart(statsService.typeDistribution) { item in
                    SectorMark(
                        angle: .value("金额", item.amount),
                        innerRadius: .ratio(0.5),
                        angularInset: 1
                    )
                    .foregroundStyle(by: .value("类型", item.type.rawValue))
                    .annotation(position: .overlay) {
                        Text("\(item.percentage, specifier: "%.0f")%")
                            .font(.caption2)
                            .foregroundColor(.white)
                    }
                }
                .frame(height: 200)
            }
        }
        .padding()
        .background(Color(.systemBackground))
        .cornerRadius(12)
        .shadow(color: .black.opacity(0.05), radius: 5)
        .sheet(isPresented: $showingTypeDetail) {
            TypeDistributionDetailView(distribution: statsService.typeDistribution)
        }
    }
    
    // 盈亏趋势卡片
    private var profitTrendCard: some View {
        VStack(alignment: .leading, spacing: 16) {
            HStack {
                Text("盈亏趋势")
                    .font(.headline)
                
                Spacer()
                
                Picker("时间范围", selection: $selectedTimeRange) {
                    ForEach(timeRanges, id: \.self) { days in
                        Text("\(days)天").tag(days)
                    }
                }
                .pickerStyle(.segmented)
                .frame(width: 200)
            }
            
            if statsService.profitTrend.isEmpty {
                emptyStateView(title: "暂无趋势数据")
            } else {
                Chart(statsService.profitTrend) { item in
                    LineMark(
                        x: .value("日期", item.date, unit: .day),
                        y: .value("盈亏", item.profit)
                    )
                    .foregroundStyle(.blue)
                    
                    AreaMark(
                        x: .value("日期", item.date, unit: .day),
                        y: .value("盈亏", item.profit)
                    )
                    .foregroundStyle(
                        LinearGradient(
                            colors: [.blue.opacity(0.3), .blue.opacity(0.1)],
                            startPoint: .top,
                            endPoint: .bottom
                        )
                    )
                }
                .frame(height: 200)
                .chartXAxis {
                    AxisMarks(values: .stride(by: .day, count: 7)) { value in
                        AxisGridLine()
                        AxisTick()
                        AxisValueLabel {
                            if let date = value.as(Date.self) {
                                Text(date, format: .dateTime.month().day())
                                    .font(.caption2)
                            }
                        }
                    }
                }
            }
        }
        .padding()
        .background(Color(.systemBackground))
        .cornerRadius(12)
        .shadow(color: .black.opacity(0.05), radius: 5)
    }
    
    // 统计总结卡片
    private var statsSummaryCard: some View {
        VStack(alignment: .leading, spacing: 16) {
            Text("数据总结")
                .font(.headline)
            
            Grid(alignment: .leading, horizontalSpacing: 20, verticalSpacing: 12) {
                GridRow {
                    StatSummaryItem(
                        icon: "ticket.fill",
                        title: "总票数",
                        value: "\(statsService.monthlyStats.currentMonth.ticketCount)",
                        color: .blue
                    )
                    
                    StatSummaryItem(
                        icon: "percent",
                        title: "中奖率",
                        value: "\(statsService.monthlyStats.currentMonth.winRate, default: "%.1f")%",
                        color: .green
                    )
                }
                
                GridRow {
                    StatSummaryItem(
                        icon: "dollarsign.circle.fill",
                        title: "平均投注",
                        value: Formatters.formatCurrency(statsService.monthlyStats.currentMonth.averageBet),
                        color: .orange
                    )
                    
                    StatSummaryItem(
                        icon: "chart.line.uptrend.xyaxis",
                        title: "最佳类型",
                        value: bestTypeName,
                        color: .purple
                    )
                }
            }
        }
        .padding()
        .background(Color(.systemBackground))
        .cornerRadius(12)
        .shadow(color: .black.opacity(0.05), radius: 5)
    }
    
    // 计算最佳类型
    private var bestTypeName: String {
        if let bestType = statsService.typeDistribution.first {
            return bestType.type.rawValue
        }
        return "无数据"
    }
    
    // 空状态视图
    private func emptyStateView(title: String) -> some View {
        VStack(spacing: 12) {
            Image(systemName: "chart.bar.doc.horizontal")
                .font(.system(size: 40))
                .foregroundColor(.gray.opacity(0.5))
            
            Text(title)
                .font(.subheadline)
                .foregroundColor(.secondary)
            
            Text("添加更多彩票记录以查看统计")
                .font(.caption)
                .foregroundColor(.gray)
        }
        .frame(height: 150)
        .frame(maxWidth: .infinity)
    }
}

// 类型分布详情视图
struct TypeDistributionDetailView: View {
    let distribution: [TypeDistribution]
    
    var body: some View {
        NavigationView {
            List(distribution) { item in
                HStack {
                    // 颜色标识
                    Circle()
                        .fill(colorForType(item.type))
                        .frame(width: 12, height: 12)
                    
                    Text(item.type.rawValue)
                        .font(.body)
                    
                    Spacer()
                    
                    VStack(alignment: .trailing) {
                        Text(Formatters.formatCurrency(item.amount))
                            .font(.headline)
                        
                        Text("\(item.percentage, specifier: "%.1f")%")
                            .font(.caption)
                            .foregroundColor(.secondary)
                    }
                }
                .padding(.vertical, 4)
            }
            .navigationTitle("类型分布详情")
            .navigationBarTitleDisplayMode(.inline)
        }
    }
    
    private func colorForType(_ type: LotteryType) -> Color {
        switch type {
        case .doubleColorBall: return .red
        case .superLotto: return .blue
        case .happy8: return .green
        case .sevenStar: return .purple
        case .other: return .gray
        }
    }
}

// 统计项目组件
struct StatItem: View {
    let title: String
    let value: String
    let color: Color
    
    var body: some View {
        VStack(spacing: 6) {
            Text(title)
                .font(.caption)
                .foregroundColor(.secondary)
            
            Text(value)
                .font(.system(size: 16, weight: .semibold))
                .foregroundColor(color)
        }
        .frame(maxWidth: .infinity)
    }
}

// 统计总结项目
struct StatSummaryItem: View {
    let icon: String
    let title: String
    let value: String
    let color: Color
    
    var body: some View {
        HStack(spacing: 12) {
            // 图标
            ZStack {
                Circle()
                    .fill(color.opacity(0.1))
                    .frame(width: 40, height: 40)
                
                Image(systemName: icon)
                    .font(.system(size: 18))
                    .foregroundColor(color)
            }
            
            // 文本
            VStack(alignment: .leading, spacing: 2) {
                Text(title)
                    .font(.caption)
                    .foregroundColor(.secondary)
                
                Text(value)
                    .font(.system(size: 16, weight: .semibold))
                    .foregroundColor(.primary)
            }
        }
        .frame(maxWidth: .infinity, alignment: .leading)
    }
}

// 预览
struct StatisticsView_Previews: PreviewProvider {
    static var previews: some View {
        NavigationView {
            StatisticsView()
                .environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
        }
    }
}
