import SwiftUI
import SwiftData
import Charts

struct StatisticsView: View {
    @Query private var expenseRecords: [ExpenseRecord]
    @StateObject private var currencyManager = CurrencyManager.shared
    @State private var selectedPeriod: TimePeriod = .month
    @State private var selectedTrendItem: TrendData?
    @State private var selectedCategoryItem: CategoryStat?
    
    enum TimePeriod: String, CaseIterable {
        case month = "月"
        case quarter = "季度"
        case year = "年"
    }
    
    // 计算当前周期的支出数据
    private var currentPeriodExpense: Double {
        let filteredRecords = getRecordsForPeriod(selectedPeriod)
        return filteredRecords.reduce(0) { $0 + $1.amount }
    }
    
    // 计算日均支出
    private var dailyAverageExpense: Double {
        let filteredRecords = getRecordsForPeriod(selectedPeriod)
        let days = getDaysInPeriod(selectedPeriod)
        return days > 0 ? filteredRecords.reduce(0) { $0 + $1.amount } / Double(days) : 0
    }
    
    // 分类统计数据
    private var categoryStats: [CategoryStat] {
        let filteredRecords = getRecordsForPeriod(selectedPeriod)
        let grouped = Dictionary(grouping: filteredRecords) { $0.category.name }
        
        return grouped.compactMap { (categoryName, records) in
            let total = records.reduce(0) { $0 + $1.amount }
            let percentage = currentPeriodExpense > 0 ? (total / currentPeriodExpense) * 100 : 0
            return CategoryStat(
                name: categoryName,
                amount: total,
                percentage: percentage,
                color: records.first?.category.colorHex ?? "#6B7280",
                iconName: records.first?.category.iconName ?? "circle"
            )
        }.sorted { $0.amount > $1.amount }
    }
    
    var body: some View {
        NavigationView {
            ZStack {
                // 背景渐变
                LinearGradient(
                    gradient: Gradient(colors: [
                        Color(red: 1.0, green: 0.96, blue: 0.9),
                        Color(red: 1.0, green: 0.88, blue: 0.7),
                        Color(red: 1.0, green: 0.8, blue: 0.8),
                        Color(red: 1.0, green: 0.82, blue: 0.86)
                    ]),
                    startPoint: .topLeading,
                    endPoint: .bottomTrailing
                )
                .ignoresSafeArea()
                
                ScrollView {
                    VStack(spacing: 20) {
                        // 时间周期选择器
                        periodSelector
                        
                        // 统计卡片
                        summaryCards
                        
                        // 趋势图表
                        trendChart
                        
                        // 分类分布图表
                        categoryDistributionChart
                        
                        // 分类明细
                        categoryBreakdown
                        
                        Spacer(minLength: 100)
                    }
                    .padding(.horizontal, 24)
                    .padding(.top, 20)
                }
            }
            .navigationTitle("统计")
            .navigationBarTitleDisplayMode(.large)
        }
    }
    
    private var periodSelector: some View {
        HStack(spacing: 4) {
            ForEach(TimePeriod.allCases, id: \.self) { period in
                Button(action: {
                    selectedPeriod = period
                }) {
                    Text(period.rawValue)
                        .font(.system(size: 16, weight: .medium))
                        .foregroundColor(selectedPeriod == period ? .white : .primary)
                        .padding(.horizontal, 24)
                        .padding(.vertical, 12)
                        .background(
                            Group {
                                if selectedPeriod == period {
                                    LinearGradient(
                                        gradient: Gradient(colors: [
                                            Color(red: 0.4, green: 0.5, blue: 0.9),
                                            Color(red: 0.46, green: 0.29, blue: 0.64)
                                        ]),
                                        startPoint: .topLeading,
                                        endPoint: .bottomTrailing
                                    )
                                } else {
                                    Color.clear
                                }
                            }
                        )
                        .clipShape(RoundedRectangle(cornerRadius: 12))
                }
            }
        }
        .padding(4)
        .background(
            RoundedRectangle(cornerRadius: 16)
                .fill(Color.gray.opacity(0.1))
        )
    }
    
    private var summaryCards: some View {
        HStack(spacing: 16) {
            // 总支出卡片
            VStack(spacing: 8) {
                Text(currencyManager.formatAmount(currentPeriodExpense))
                    .font(.system(size: 24, weight: .bold, design: .rounded))
                    .foregroundColor(.primary)
                
                Text("本\(selectedPeriod.rawValue)支出")
                    .font(.caption)
                    .foregroundColor(.secondary)
                
                HStack(spacing: 4) {
                    Image(systemName: "arrow.down")
                        .font(.caption)
                        .foregroundColor(.green)
                    Text("-8.5%")
                        .font(.caption)
                        .foregroundColor(.green)
                }
            }
            .frame(maxWidth: .infinity)
            .padding(.vertical, 20)
            .background(
                RoundedRectangle(cornerRadius: 16)
                    .fill(.ultraThinMaterial)
                    .shadow(color: .black.opacity(0.1), radius: 8, x: 0, y: 4)
            )
            
            // 日均支出卡片
            VStack(spacing: 8) {
                Text(currencyManager.formatAmount(dailyAverageExpense))
                    .font(.system(size: 24, weight: .bold, design: .rounded))
                    .foregroundColor(.primary)
                
                Text("日均支出")
                    .font(.caption)
                    .foregroundColor(.secondary)
                
                HStack(spacing: 4) {
                    Image(systemName: "arrow.up")
                        .font(.caption)
                        .foregroundColor(.red)
                    Text("+12.3%")
                        .font(.caption)
                        .foregroundColor(.red)
                }
            }
            .frame(maxWidth: .infinity)
            .padding(.vertical, 20)
            .background(
                RoundedRectangle(cornerRadius: 16)
                    .fill(.ultraThinMaterial)
                    .shadow(color: .black.opacity(0.1), radius: 8, x: 0, y: 4)
            )
        }
    }
    
    private var trendChart: some View {
        VStack(alignment: .leading, spacing: 16) {
            HStack {
                Text("支出趋势")
                    .font(.headline)
                    .foregroundColor(.primary)
                
                Spacer()
                
                Image(systemName: "chart.line.uptrend.xyaxis")
                    .foregroundColor(.blue)
            }
            
            // 使用真实数据的图表展示
            let trendData = getRealTrendData()
            let maxAmount = trendData.map { $0.amount }.max() ?? 1
            
            VStack(spacing: 8) {
                HStack(alignment: .bottom, spacing: 8) {
                    ForEach(trendData, id: \.month) { data in
                        VStack(spacing: 4) {
                            // 显示金额数字
                            if data.amount > 0 {
                                Text(currencyManager.formatAmount(data.amount))
                                    .font(.caption2)
                                    .foregroundColor(.primary)
                                    .opacity(selectedTrendItem?.month == data.month ? 1.0 : 0.7)
                            }
                            
                            Spacer()
                            
                            RoundedRectangle(cornerRadius: 4)
                                .fill(
                                    LinearGradient(
                                        gradient: Gradient(colors: [
                                            selectedTrendItem?.month == data.month ? Color.blue.opacity(0.8) : Color.orange.opacity(0.8),
                                            selectedTrendItem?.month == data.month ? Color.purple.opacity(0.6) : Color.pink.opacity(0.6)
                                        ]),
                                        startPoint: .top,
                                        endPoint: .bottom
                                    )
                                )
                                .frame(width: 30, height: maxAmount > 0 ? max(CGFloat(data.amount / maxAmount * 80), 2) : 2)
                                .scaleEffect(selectedTrendItem?.month == data.month ? 1.1 : 1.0)
                                .animation(.spring(response: 0.3), value: selectedTrendItem?.month)
                            
                            Text(data.month)
                                .font(.caption2)
                                .foregroundColor(.secondary)
                                .fontWeight(selectedTrendItem?.month == data.month ? .semibold : .regular)
                        }
                        .frame(height: 100)
                        .onTapGesture {
                            if selectedTrendItem?.month == data.month {
                                selectedTrendItem = nil
                            } else {
                                selectedTrendItem = data
                            }
                        }
                    }
                }
                .frame(height: 120)
            }
            .padding(16)
        }
        .padding(20)
        .background(
            RoundedRectangle(cornerRadius: 16)
                .fill(.ultraThinMaterial)
                .shadow(color: .black.opacity(0.1), radius: 8, x: 0, y: 4)
        )
    }
    
    private var categoryDistributionChart: some View {
        VStack(alignment: .leading, spacing: 16) {
            HStack {
                Text("分类分布")
                    .font(.headline)
                    .foregroundColor(.primary)
                
                Spacer()
                
                Image(systemName: "chart.pie")
                    .foregroundColor(.purple)
            }
            
            // 修复高度和对齐的柱状图展示
            let maxPercentage = categoryStats.prefix(5).map { $0.percentage }.max() ?? 1
            
            HStack(alignment: .bottom, spacing: 12) {
                ForEach(categoryStats.prefix(5), id: \.name) { stat in
                    VStack(spacing: 4) {
                        // 显示百分比数字
                        if stat.percentage > 0 {
                            Text("\(Int(stat.percentage))%")
                                .font(.caption2)
                                .foregroundColor(.primary)
                                .opacity(selectedCategoryItem?.name == stat.name ? 1.0 : 0.7)
                        }
                        
                        Spacer()
                        
                        RoundedRectangle(cornerRadius: 4)
                            .fill(Color(hex: stat.color))
                            .frame(width: 40, height: maxPercentage > 0 ? max(CGFloat(stat.percentage / maxPercentage * 80), 2) : 2)
                            .scaleEffect(selectedCategoryItem?.name == stat.name ? 1.1 : 1.0)
                            .animation(.spring(response: 0.3), value: selectedCategoryItem?.name)
                        
                        Text(stat.name)
                            .font(.caption2)
                            .foregroundColor(.secondary)
                            .lineLimit(1)
                            .fontWeight(selectedCategoryItem?.name == stat.name ? .semibold : .regular)
                    }
                    .frame(height: 100)
                    .onTapGesture {
                        if selectedCategoryItem?.name == stat.name {
                            selectedCategoryItem = nil
                        } else {
                            selectedCategoryItem = stat
                        }
                    }
                }
                
                if categoryStats.count > 5 {
                    VStack(spacing: 4) {
                        Spacer()
                        
                        RoundedRectangle(cornerRadius: 4)
                            .fill(Color.gray.opacity(0.6))
                            .frame(width: 40, height: 20)
                        
                        Text("其他")
                            .font(.caption2)
                            .foregroundColor(.secondary)
                    }
                    .frame(height: 100)
                }
            }
            .frame(height: 120)
        }
        .padding(20)
        .background(
            RoundedRectangle(cornerRadius: 16)
                .fill(.ultraThinMaterial)
                .shadow(color: .black.opacity(0.1), radius: 8, x: 0, y: 4)
        )
    }
    
    private var categoryBreakdown: some View {
        VStack(alignment: .leading, spacing: 16) {
            Text("分类明细")
                .font(.headline)
                .foregroundColor(.primary)
            
            VStack(spacing: 12) {
                ForEach(categoryStats, id: \.name) { stat in
                    HStack {
                        HStack(spacing: 12) {
                            Circle()
                                .fill(Color(hex: stat.color))
                                .frame(width: 16, height: 16)
                            
                            Text(stat.name)
                                .font(.body)
                                .foregroundColor(.primary)
                        }
                        
                        Spacer()
                        
                        VStack(alignment: .trailing, spacing: 2) {
                            Text(currencyManager.formatAmount(stat.amount))
                                .font(.system(size: 16, weight: .semibold))
                                .foregroundColor(.primary)
                            
                            Text("\(stat.percentage, specifier: "%.1f")%")
                                .font(.caption)
                                .foregroundColor(.secondary)
                        }
                    }
                    .padding(.vertical, 4)
                }
            }
        }
        .padding(20)
        .background(
            RoundedRectangle(cornerRadius: 16)
                .fill(.ultraThinMaterial)
                .shadow(color: .black.opacity(0.1), radius: 8, x: 0, y: 4)
        )
    }
    
    // 辅助方法
    private func getRecordsForPeriod(_ period: TimePeriod) -> [ExpenseRecord] {
        let calendar = Calendar.current
        let now = Date()
        
        switch period {
        case .month:
            return expenseRecords.filter { record in
                calendar.isDate(record.timestamp, equalTo: now, toGranularity: .month)
            }
        case .quarter:
            let currentQuarter = calendar.component(.quarter, from: now)
            let currentYear = calendar.component(.year, from: now)
            return expenseRecords.filter { record in
                calendar.component(.quarter, from: record.timestamp) == currentQuarter &&
                calendar.component(.year, from: record.timestamp) == currentYear
            }
        case .year:
            return expenseRecords.filter { record in
                calendar.isDate(record.timestamp, equalTo: now, toGranularity: .year)
            }
        }
    }
    
    private func getDaysInPeriod(_ period: TimePeriod) -> Int {
        let calendar = Calendar.current
        let now = Date()
        
        switch period {
        case .month:
            return calendar.range(of: .day, in: .month, for: now)?.count ?? 30
        case .quarter:
            return 90
        case .year:
            return calendar.range(of: .day, in: .year, for: now)?.count ?? 365
        }
    }
    
    private func getRealTrendData() -> [TrendData] {
        let calendar = Calendar.current
        let now = Date()
        var trendData: [TrendData] = []
        
        // 根据选择的周期生成真实数据
        switch selectedPeriod {
        case .month:
            // 显示最近6个月的数据
            for i in (0..<6).reversed() {
                if let date = calendar.date(byAdding: .month, value: -i, to: now) {
                    let monthRecords = expenseRecords.filter { record in
                        calendar.isDate(record.timestamp, equalTo: date, toGranularity: .month)
                    }
                    let total = monthRecords.reduce(0) { $0 + $1.amount }
                    let monthFormatter = DateFormatter()
                    monthFormatter.dateFormat = "M月"
                    let monthName = monthFormatter.string(from: date)
                    trendData.append(TrendData(month: monthName, amount: total))
                }
            }
        case .quarter:
            // 显示最近4个季度的数据
            for i in (0..<4).reversed() {
                // 计算季度的开始月份
                let monthsBack = i * 3
                if let quarterStartDate = calendar.date(byAdding: .month, value: -monthsBack, to: now) {
                    let quarter = calendar.component(.quarter, from: quarterStartDate)
                    let year = calendar.component(.year, from: quarterStartDate)
                    let quarterRecords = expenseRecords.filter { record in
                        calendar.component(.quarter, from: record.timestamp) == quarter &&
                        calendar.component(.year, from: record.timestamp) == year
                    }
                    let total = quarterRecords.reduce(0) { $0 + $1.amount }
                    trendData.append(TrendData(month: "Q\(quarter)", amount: total))
                }
            }
        case .year:
            // 显示最近5年的数据
            for i in (0..<5).reversed() {
                if let date = calendar.date(byAdding: .year, value: -i, to: now) {
                    let yearRecords = expenseRecords.filter { record in
                        calendar.isDate(record.timestamp, equalTo: date, toGranularity: .year)
                    }
                    let total = yearRecords.reduce(0) { $0 + $1.amount }
                    let year = calendar.component(.year, from: date)
                    trendData.append(TrendData(month: "\(year)", amount: total))
                }
            }
        }
        
        return trendData
    }
}

struct CategoryStat {
    let name: String
    let amount: Double
    let percentage: Double
    let color: String
    let iconName: String
}

struct TrendData {
    let month: String
    let amount: Double
}

#Preview {
    StatisticsView()
        .modelContainer(for: [ExpenseRecord.self, ExpenseCategory.self], inMemory: true)
} 