import SwiftUI
import SwiftData

struct ManualInputView: View {
    @Environment(\.dismiss) private var dismiss
    @Environment(\.modelContext) private var modelContext
    @Query private var categories: [ExpenseCategory]
    
    @State private var amount: String = ""
    @State private var title: String = ""
    @State private var selectedCategory: ExpenseCategory?
    @State private var selectedDate = Date()
    
    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: 24) {
                        // 金额输入
                        VStack(alignment: .leading, spacing: 8) {
                            Text("金额")
                                .font(.headline)
                                .foregroundColor(.primary)
                            
                            TextField("0.00", text: $amount)
                                .font(.title2)
                                .keyboardType(.decimalPad)
                                .padding(16)
                                .background(
                                    RoundedRectangle(cornerRadius: 12)
                                        .fill(.ultraThinMaterial)
                                        .stroke(Color.gray.opacity(0.3), lineWidth: 1)
                                )
                        }
                        
                        // 标题输入
                        VStack(alignment: .leading, spacing: 8) {
                            Text("标题")
                                .font(.headline)
                                .foregroundColor(.primary)
                            
                            TextField("例如：午餐、咖啡", text: $title)
                                .font(.body)
                                .padding(16)
                                .background(
                                    RoundedRectangle(cornerRadius: 12)
                                        .fill(.ultraThinMaterial)
                                        .stroke(Color.gray.opacity(0.3), lineWidth: 1)
                                )
                        }
                        
                        // 分类选择
                        VStack(alignment: .leading, spacing: 12) {
                            Text("分类")
                                .font(.headline)
                                .foregroundColor(.primary)
                            
                            LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: 3), spacing: 12) {
                                ForEach(categories, id: \.id) { category in
                                    CategorySelectionItem(
                                        category: category,
                                        isSelected: selectedCategory?.id == category.id
                                    ) {
                                        selectedCategory = category
                                    }
                                }
                            }
                        }
                        
                        // 时间选择
                        VStack(alignment: .leading, spacing: 8) {
                            Text("时间")
                                .font(.headline)
                                .foregroundColor(.primary)
                            
                            DatePicker("选择时间", selection: $selectedDate, displayedComponents: [.date, .hourAndMinute])
                                .padding(16)
                                .background(
                                    RoundedRectangle(cornerRadius: 12)
                                        .fill(.ultraThinMaterial)
                                        .stroke(Color.gray.opacity(0.3), lineWidth: 1)
                                )
                        }
                    }
                    .padding(.horizontal, 24)
                    .padding(.top, 20)
                }
            }
            .navigationTitle("添加支出")
            .navigationBarTitleDisplayMode(.large)
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Button("取消") {
                        dismiss()
                    }
                }
                
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button("保存") {
                        saveExpense()
                    }
                    .disabled(!isFormValid)
                }
            }
        }
    }
    
    private var isFormValid: Bool {
        !amount.isEmpty && 
        !title.isEmpty && 
        selectedCategory != nil &&
        Double(amount) != nil
    }
    
    private func saveExpense() {
        guard let amountValue = Double(amount),
              let category = selectedCategory else { return }
        
        let newRecord = ExpenseRecord(
            amount: amountValue,
            title: title,
            category: category,
            timestamp: selectedDate
        )
        
        modelContext.insert(newRecord)
        
        do {
            try modelContext.save()
            dismiss()
        } catch {
            print("保存失败: \(error)")
        }
    }
}

struct CategorySelectionItem: View {
    let category: ExpenseCategory
    let isSelected: Bool
    let onTap: () -> Void
    
    var body: some View {
        VStack(spacing: 8) {
            Image(systemName: category.iconName)
                .font(.title2)
                .foregroundColor(isSelected ? .white : Color(hex: category.colorHex))
                .frame(width: 40, height: 40)
                .background(
                    Circle()
                        .fill(isSelected ? Color(hex: category.colorHex) : Color(hex: category.colorHex).opacity(0.1))
                )
            
            Text(category.name)
                .font(.caption)
                .foregroundColor(.primary)
        }
        .padding(.vertical, 12)
        .frame(maxWidth: .infinity)
        .background(
            RoundedRectangle(cornerRadius: 12)
                .fill(isSelected ? Color.white.opacity(0.8) : Color.clear)
                .stroke(isSelected ? Color(hex: category.colorHex) : Color.clear, lineWidth: 2)
        )
        .onTapGesture {
            onTap()
        }
    }
}

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