import SwiftUI
import SwiftData

@available(iOS 13.0, *)
@MainActor
struct AIParsingResultView: View {
    @Environment(\.dismiss) private var dismiss
    @Environment(\.modelContext) private var modelContext
    @Query private var categories: [ExpenseCategory]
    
    let expenses: [ExpenseInfo]
    let onSave: () -> Void
    
    @State private var editableExpenses: [EditableExpense] = []
    @State private var showingSaveAlert = false
    @State private var saveMessage = ""
    
    var body: some View {
        NavigationView {
            ZStack {
                // 背景渐变
                LinearGradient(
                    gradient: Gradient(colors: [
                        Color(red: 0.95, green: 0.97, blue: 1.0),
                        Color(red: 0.9, green: 0.95, blue: 1.0)
                    ]),
                    startPoint: .topLeading,
                    endPoint: .bottomTrailing
                )
                .ignoresSafeArea()
                
                ScrollView {
                    VStack(spacing: 20) {
                        // 标题
                        VStack(spacing: 8) {
                            Image(systemName: "brain.head.profile")
                                .font(.system(size: 40))
                                .foregroundColor(.blue)
                            
                            Text("AI解析结果")
                                .font(.title2)
                                .fontWeight(.bold)
                            
                            Text("请确认并编辑记账信息")
                                .font(.caption)
                                .foregroundColor(.secondary)
                        }
                        .padding(.top, 20)
                        
                        // 记账条目列表
                        LazyVStack(spacing: 16) {
                            ForEach(editableExpenses.indices, id: \.self) { index in
                                ExpenseEditCard(
                                    expense: $editableExpenses[index],
                                    categories: categories,
                                    onDelete: {
                                        editableExpenses.remove(at: index)
                                    }
                                )
                            }
                        }
                        .padding(.horizontal, 16)
                        
                        // 添加新条目按钮
                        Button(action: addNewExpense) {
                            HStack {
                                Image(systemName: "plus.circle.fill")
                                Text("添加记账条目")
                            }
                            .font(.headline)
                            .foregroundColor(.blue)
                            .padding(.vertical, 12)
                            .padding(.horizontal, 20)
                            .background(
                                RoundedRectangle(cornerRadius: 12)
                                    .fill(.ultraThinMaterial)
                                    .stroke(Color.blue, lineWidth: 1)
                            )
                        }
                        .padding(.top, 10)
                        
                        Spacer(minLength: 100)
                    }
                }
            }
            .navigationTitle("确认记账")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Button("取消") {
                        dismiss()
                    }
                }
                
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button("保存全部") {
                        saveAllExpenses()
                    }
                    .fontWeight(.medium)
                    .disabled(editableExpenses.isEmpty)
                }
            }
        }
        .onAppear {
            setupEditableExpenses()
        }
        .alert("提示", isPresented: $showingSaveAlert) {
            Button("确定") {
                if saveMessage.contains("成功") {
                    onSave()
                    dismiss()
                }
            }
        } message: {
            Text(saveMessage)
        }
    }
    
    private func setupEditableExpenses() {
        editableExpenses = expenses.map { expense in
            EditableExpense(
                amount: String(expense.amount),
                title: expense.title,
                selectedCategory: findCategory(name: expense.category),
                timestamp: Date()
            )
        }
    }
    
    private func findCategory(name: String) -> ExpenseCategory? {
        return categories.first { $0.name == name } ?? categories.first { $0.name == "其他" }
    }
    
    private func addNewExpense() {
        let newExpense = EditableExpense(
            amount: "",
            title: "",
            selectedCategory: categories.first { $0.name == "其他" },
            timestamp: Date()
        )
        editableExpenses.append(newExpense)
    }
    
    private func saveAllExpenses() {
        var successCount = 0
        var errorCount = 0
        
        for editableExpense in editableExpenses {
            guard let amountValue = Double(editableExpense.amount),
                  !editableExpense.title.isEmpty,
                  let category = editableExpense.selectedCategory else {
                errorCount += 1
                continue
            }
            
            let newRecord = ExpenseRecord(
                amount: amountValue,
                title: editableExpense.title,
                category: category,
                timestamp: editableExpense.timestamp
            )
            
            modelContext.insert(newRecord)
            successCount += 1
        }
        
        do {
            try modelContext.save()
            saveMessage = "成功保存 \(successCount) 条记录"
            if errorCount > 0 {
                saveMessage += "，\(errorCount) 条记录因数据不完整未保存"
            }
        } catch {
            saveMessage = "保存失败: \(error.localizedDescription)"
        }
        
        showingSaveAlert = true
    }
}

struct EditableExpense {
    var amount: String
    var title: String
    var selectedCategory: ExpenseCategory?
    var timestamp: Date
}

struct ExpenseEditCard: View {
    @Binding var expense: EditableExpense
    let categories: [ExpenseCategory]
    let onDelete: () -> Void
    
    @State private var showingDatePicker = false
    
    var body: some View {
        VStack(spacing: 16) {
            // 卡片标题和删除按钮
            HStack {
                Text("记账条目")
                    .font(.headline)
                    .foregroundColor(.primary)
                
                Spacer()
                
                Button(action: onDelete) {
                    Image(systemName: "trash")
                        .foregroundColor(.red)
                }
            }
            
            // 金额输入
            VStack(alignment: .leading, spacing: 8) {
                Text("金额")
                    .font(.subheadline)
                    .foregroundColor(.secondary)
                
                TextField("请输入金额", text: $expense.amount)
                    .keyboardType(.decimalPad)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
            }
            
            // 标题输入
            VStack(alignment: .leading, spacing: 8) {
                Text("描述")
                    .font(.subheadline)
                    .foregroundColor(.secondary)
                
                TextField("请输入消费描述", text: $expense.title)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
            }
            
            // 分类选择
            VStack(alignment: .leading, spacing: 8) {
                Text("分类")
                    .font(.subheadline)
                    .foregroundColor(.secondary)
                
                LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: 3), spacing: 12) {
                    ForEach(categories, id: \.id) { category in
                        VStack {
                            Image(systemName: category.iconName)
                                .font(.title2)
                                .foregroundColor(expense.selectedCategory?.id == category.id ? .white : Color(hex: category.colorHex))
                                .frame(width: 40, height: 40)
                                .background(
                                    Circle()
                                        .fill(expense.selectedCategory?.id == category.id ? Color(hex: category.colorHex) : Color(hex: category.colorHex).opacity(0.1))
                                        .overlay(
                                            Circle()
                                                .stroke(expense.selectedCategory?.id == category.id ? Color(hex: category.colorHex) : Color.clear, lineWidth: 3)
                                        )
                                )
                            
                            Text(category.name)
                                .font(.caption)
                                .fontWeight(expense.selectedCategory?.id == category.id ? .bold : .regular)
                                .foregroundColor(expense.selectedCategory?.id == category.id ? Color(hex: category.colorHex) : .primary)
                        }
                        .scaleEffect(expense.selectedCategory?.id == category.id ? 1.1 : 1.0)
                        .animation(.easeInOut(duration: 0.2), value: expense.selectedCategory?.id)
                        .onTapGesture {
                            expense.selectedCategory = category
                        }
                    }
                }
            }
            
            // 时间选择
            VStack(alignment: .leading, spacing: 8) {
                Text("时间")
                    .font(.subheadline)
                    .foregroundColor(.secondary)
                
                Button(action: { showingDatePicker = true }) {
                    HStack {
                        Text(expense.timestamp, style: .date)
                        Text(expense.timestamp, style: .time)
                        Spacer()
                        Image(systemName: "calendar")
                    }
                    .padding(.horizontal, 12)
                    .padding(.vertical, 8)
                    .background(
                        RoundedRectangle(cornerRadius: 8)
                            .fill(Color(.systemGray6))
                    )
                }
                .foregroundColor(.primary)
            }
        }
        .padding(16)
        .background(
            RoundedRectangle(cornerRadius: 12)
                .fill(.ultraThinMaterial)
                .stroke(Color.gray.opacity(0.3), lineWidth: 1)
        )
        .sheet(isPresented: $showingDatePicker) {
            NavigationView {
                DatePicker("选择时间", selection: $expense.timestamp, displayedComponents: [.date, .hourAndMinute])
                    .datePickerStyle(WheelDatePickerStyle())
                    .navigationTitle("选择时间")
                    .navigationBarTitleDisplayMode(.inline)
                    .toolbar {
                        ToolbarItem(placement: .navigationBarTrailing) {
                            Button("完成") {
                                showingDatePicker = false
                            }
                        }
                    }
            }
        }
    }
}



#Preview {
    AIParsingResultView(
        expenses: [
            ExpenseInfo(amount: 45.0, title: "午餐", category: "餐饮"),
            ExpenseInfo(amount: 28.0, title: "咖啡", category: "餐饮")
        ],
        onSave: {}
    )
    .modelContainer(for: [ExpenseRecord.self, ExpenseCategory.self], inMemory: true)
} 