import SwiftUI
import SwiftData

struct HomeView: View {
    @Environment(\.modelContext) private var modelContext
    @Query private var expenseRecords: [ExpenseRecord]
    @StateObject private var currencyManager = CurrencyManager.shared
    @State private var showingManualInput = false
    @State private var showingVoiceInput = false
    
    // 计算本月支出
    private var monthlyExpense: Double {
        let calendar = Calendar.current
        let now = Date()
        let monthlyRecords = expenseRecords.filter { record in
            calendar.isDate(record.timestamp, equalTo: now, toGranularity: .month)
        }
        return monthlyRecords.reduce(0) { $0 + $1.amount }
    }
    
    // 计算今日记录
    private var todayRecords: [ExpenseRecord] {
        let calendar = Calendar.current
        let today = Date()
        return expenseRecords.filter { record in
            calendar.isDate(record.timestamp, inSameDayAs: today)
        }.sorted { $0.timestamp > $1.timestamp }
    }
    
    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) {
                        // 月支出概览
                        monthlyOverviewCard
                        
                        // 操作按钮
                        actionButtons
                        
                        // 今日记录
                        todayRecordsSection
                        
                        Spacer(minLength: 100) // 为底部TabBar留空间
                    }
                    .padding(.horizontal, 24)
                    .padding(.top, 20)
                }
            }
            .navigationTitle("记账")
            .navigationBarTitleDisplayMode(.large)
        }
        .sheet(isPresented: $showingManualInput) {
            ManualInputView()
        }
        .sheet(isPresented: $showingVoiceInput) {
            VoiceInputView()
        }
    }
    
    private var monthlyOverviewCard: some View {
        VStack(spacing: 12) {
            Text("本月支出")
                .font(.subheadline)
                .foregroundColor(.secondary)
            
            Text(currencyManager.formatAmountWithDecimals(monthlyExpense))
                .font(.system(size: 36, weight: .bold, design: .rounded))
                .foregroundColor(.primary)
            
            Text("较上月 +12.5%")
                .font(.caption)
                .foregroundColor(.secondary)
        }
        .frame(maxWidth: .infinity)
        .padding(.vertical, 24)
        .background(
            RoundedRectangle(cornerRadius: 20)
                .fill(.ultraThinMaterial)
                .shadow(color: .black.opacity(0.1), radius: 10, x: 0, y: 4)
        )
    }
    
    private var actionButtons: some View {
        HStack(spacing: 16) {
            // 语音输入按钮
            VStack(spacing: 12) {
                Image(systemName: "mic.fill")
                    .font(.title)
                    .foregroundColor(.white)
                
                VStack(spacing: 4) {
                    Text("语音输入")
                        .font(.system(size: 16, weight: .semibold))
                        .foregroundColor(.white)
                    
                    Text("长按开始录音")
                        .font(.caption)
                        .foregroundColor(.white.opacity(0.8))
                }
            }
            .frame(maxWidth: .infinity)
            .padding(.vertical, 24)
            .background(
                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
                )
            )
            .clipShape(RoundedRectangle(cornerRadius: 20))
            .shadow(color: Color(red: 0.4, green: 0.5, blue: 0.9).opacity(0.3), radius: 10, x: 0, y: 4)
            .onTapGesture {
                showingVoiceInput = true
            }
            
            // 手动输入按钮
            VStack(spacing: 12) {
                Image(systemName: "pencil")
                    .font(.title)
                    .foregroundColor(.white)
                
                VStack(spacing: 4) {
                    Text("手动输入")
                        .font(.system(size: 16, weight: .semibold))
                        .foregroundColor(.white)
                    
                    Text("点击添加记录")
                        .font(.caption)
                        .foregroundColor(.white.opacity(0.8))
                }
            }
            .frame(maxWidth: .infinity)
            .padding(.vertical, 24)
            .background(
                LinearGradient(
                    gradient: Gradient(colors: [
                        Color(red: 0.94, green: 0.58, blue: 0.98),
                        Color(red: 0.96, green: 0.34, blue: 0.42)
                    ]),
                    startPoint: .topLeading,
                    endPoint: .bottomTrailing
                )
            )
            .clipShape(RoundedRectangle(cornerRadius: 20))
            .shadow(color: Color(red: 0.96, green: 0.34, blue: 0.42).opacity(0.3), radius: 10, x: 0, y: 4)
            .onTapGesture {
                showingManualInput = true
            }
        }
    }
    
    private var todayRecordsSection: some View {
        VStack(alignment: .leading, spacing: 16) {
            Text("今日记录")
                .font(.title2)
                .fontWeight(.semibold)
                .foregroundColor(.primary)
            
            if todayRecords.isEmpty {
                VStack(spacing: 12) {
                    Image(systemName: "list.bullet")
                        .font(.largeTitle)
                        .foregroundColor(.secondary)
                    
                    Text("今天还没有记录")
                        .font(.subheadline)
                        .foregroundColor(.secondary)
                }
                .frame(maxWidth: .infinity)
                .padding(.vertical, 40)
                .background(
                    RoundedRectangle(cornerRadius: 16)
                        .fill(.ultraThinMaterial)
                )
            } else {
                LazyVStack(spacing: 12) {
                    ForEach(todayRecords, id: \.id) { record in
                        ExpenseRecordRow(record: record)
                    }
                }
            }
        }
    }
}

struct ExpenseRecordRow: View {
    let record: ExpenseRecord
    let showDeleteButton: Bool
    let onDelete: (() -> Void)?
    @StateObject private var currencyManager = CurrencyManager.shared
    
    init(record: ExpenseRecord, showDeleteButton: Bool = false, onDelete: (() -> Void)? = nil) {
        self.record = record
        self.showDeleteButton = showDeleteButton
        self.onDelete = onDelete
    }
    
    var body: some View {
        HStack(spacing: 16) {
            // 分类图标
            Image(systemName: record.category.iconName)
                .font(.title3)
                .foregroundColor(Color(hex: record.category.colorHex))
                .frame(width: 40, height: 40)
                .background(
                    Circle()
                        .fill(Color(hex: record.category.colorHex).opacity(0.1))
                )
            
            // 记录信息
            VStack(alignment: .leading, spacing: 4) {
                Text(record.title)
                    .font(.system(size: 16, weight: .medium))
                    .foregroundColor(.primary)
                
                Text(record.timestamp, style: .time)
                    .font(.caption)
                    .foregroundColor(.secondary)
            }
            
            Spacer()
            
            // 金额和分类
            VStack(alignment: .trailing, spacing: 4) {
                Text(currencyManager.formatAmountWithDecimals(record.amount))
                    .font(.system(size: 16, weight: .semibold))
                    .foregroundColor(.primary)
                
                Text(record.category.name)
                    .font(.caption)
                    .foregroundColor(.secondary)
            }
            
            // 删除按钮
            if showDeleteButton {
                Button(action: {
                    onDelete?()
                }) {
                    Image(systemName: "trash")
                        .font(.system(size: 16))
                        .foregroundColor(.red)
                        .frame(width: 32, height: 32)
                        .background(
                            Circle()
                                .fill(.red.opacity(0.1))
                        )
                }
            }
        }
        .padding(16)
        .background(
            RoundedRectangle(cornerRadius: 16)
                .fill(.ultraThinMaterial)
                .shadow(color: .black.opacity(0.05), radius: 5, x: 0, y: 2)
        )
    }
}



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