import SwiftUI
import SwiftData

struct CategoryManagerView: View {
    @Environment(\.dismiss) private var dismiss
    @Environment(\.modelContext) private var modelContext
    @Query private var categories: [ExpenseCategory]
    
    @State private var showingAddCategory = false
    @State private var showingEditCategory = false
    @State private var editingCategory: ExpenseCategory?
    
    var body: some View {
        NavigationView {
            List {
                ForEach(categories, id: \.id) { category in
                    CategoryRow(category: category) {
                        editingCategory = category
                        showingEditCategory = true
                    }
                }
                .onDelete(perform: deleteCategories)
            }
            .navigationTitle("分类管理")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Button("关闭") {
                        dismiss()
                    }
                }
                
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button {
                        showingAddCategory = true
                    } label: {
                        Image(systemName: "plus")
                    }
                }
            }
        }
        .sheet(isPresented: $showingAddCategory) {
            AddEditCategoryView()
        }
        .sheet(isPresented: $showingEditCategory) {
            if let category = editingCategory {
                AddEditCategoryView(category: category)
            }
        }
    }
    
    private func deleteCategories(offsets: IndexSet) {
        for index in offsets {
            let category = categories[index]
            modelContext.delete(category)
        }
        
        do {
            try modelContext.save()
        } catch {
            print("删除分类失败: \(error)")
        }
    }
}

struct CategoryRow: View {
    let category: ExpenseCategory
    let onEdit: () -> Void
    
    var body: some View {
        HStack(spacing: 12) {
            Image(systemName: category.iconName)
                .font(.title2)
                .foregroundColor(Color(hex: category.colorHex))
                .frame(width: 40, height: 40)
                .background(
                    Circle()
                        .fill(Color(hex: category.colorHex).opacity(0.1))
                )
            
            VStack(alignment: .leading, spacing: 4) {
                Text(category.name)
                    .font(.body)
                    .foregroundColor(.primary)
                
                Text("\(category.recordCount)笔记录")
                    .font(.caption)
                    .foregroundColor(.secondary)
            }
            
            Spacer()
            
            Button("编辑") {
                onEdit()
            }
            .font(.caption)
            .foregroundColor(.blue)
        }
        .padding(.vertical, 4)
    }
}

struct AddEditCategoryView: View {
    @Environment(\.dismiss) private var dismiss
    @Environment(\.modelContext) private var modelContext
    
    let category: ExpenseCategory?
    
    @State private var name: String = ""
    @State private var selectedIcon: String = "circle"
    @State private var selectedColor: String = "#3B82F6"
    @State private var showingIconPicker = false
    @State private var showingColorPicker = false
    
    init(category: ExpenseCategory? = nil) {
        self.category = category
        if let category = category {
            _name = State(initialValue: category.name)
            _selectedIcon = State(initialValue: category.iconName)
            _selectedColor = State(initialValue: category.colorHex)
        }
    }
    
    var isEditing: Bool {
        category != nil
    }
    
    var body: some View {
        NavigationView {
            Form {
                Section("分类信息") {
                    TextField("分类名称", text: $name)
                }
                
                Section("图标和颜色") {
                    // 图标选择
                    HStack {
                        Text("图标")
                        
                        Spacer()
                        
                        Button {
                            showingIconPicker = true
                        } label: {
                            HStack {
                                Image(systemName: selectedIcon)
                                    .foregroundColor(Color(hex: selectedColor))
                                    .frame(width: 30, height: 30)
                                    .background(
                                        Circle()
                                            .fill(Color(hex: selectedColor).opacity(0.1))
                                    )
                                
                                Image(systemName: "chevron.right")
                                    .font(.caption)
                                    .foregroundColor(.secondary)
                            }
                        }
                        .buttonStyle(PlainButtonStyle())
                    }
                    
                    // 颜色选择
                    HStack {
                        Text("颜色")
                        
                        Spacer()
                        
                        Button {
                            showingColorPicker = true
                        } label: {
                            HStack {
                                Circle()
                                    .fill(Color(hex: selectedColor))
                                    .frame(width: 30, height: 30)
                                
                                Image(systemName: "chevron.right")
                                    .font(.caption)
                                    .foregroundColor(.secondary)
                            }
                        }
                        .buttonStyle(PlainButtonStyle())
                    }
                }
                
                Section("预览") {
                    HStack {
                        Image(systemName: selectedIcon)
                            .font(.title2)
                            .foregroundColor(Color(hex: selectedColor))
                            .frame(width: 50, height: 50)
                            .background(
                                Circle()
                                    .fill(Color(hex: selectedColor).opacity(0.1))
                            )
                        
                        VStack(alignment: .leading) {
                            Text(name.isEmpty ? "分类名称" : name)
                                .font(.headline)
                                .foregroundColor(name.isEmpty ? .secondary : .primary)
                        }
                        
                        Spacer()
                    }
                    .padding(.vertical, 8)
                }
            }
            .navigationTitle(isEditing ? "编辑分类" : "添加分类")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Button("取消") {
                        dismiss()
                    }
                }
                
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button("保存") {
                        saveCategory()
                    }
                    .disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
                }
            }
        }
        .sheet(isPresented: $showingIconPicker) {
            IconPickerView(selectedIcon: $selectedIcon)
        }
        .sheet(isPresented: $showingColorPicker) {
            ColorPickerView(selectedColor: $selectedColor)
        }
    }
    
    private func saveCategory() {
        let trimmedName = name.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !trimmedName.isEmpty else { return }
        
        if let existingCategory = category {
            // 编辑现有分类
            existingCategory.name = trimmedName
            existingCategory.iconName = selectedIcon
            existingCategory.colorHex = selectedColor
        } else {
            // 创建新分类
            let newCategory = ExpenseCategory(
                name: trimmedName,
                iconName: selectedIcon,
                colorHex: selectedColor
            )
            modelContext.insert(newCategory)
        }
        
        do {
            try modelContext.save()
            dismiss()
        } catch {
            print("保存分类失败: \(error)")
        }
    }
}

struct IconPickerView: View {
    @Environment(\.dismiss) private var dismiss
    @Binding var selectedIcon: String
    
    private let iconCategories: [(String, [String])] = [
        ("生活", ["house", "bed.double", "sofa", "lamp.table", "refrigerator", "washer", "tv"]),
        ("餐饮", ["fork.knife", "cup.and.saucer", "wineglass", "birthday.cake", "takeoutbag.and.cup.and.straw", "cooktop", "microwave"]),
        ("交通", ["car", "bus", "tram", "bicycle", "motorcycle", "airplane", "ferry"]),
        ("购物", ["bag", "cart", "basket", "creditcard", "giftcard", "tag", "barcode"]),
        ("娱乐", ["gamecontroller", "tv", "music.note", "film", "camera", "book", "headphones"]),
        ("运动", ["figure.walk", "figure.run", "figure.basketball", "figure.soccer", "figure.tennis", "dumbbell", "bicycle"]),
        ("医疗", ["cross", "stethoscope", "pills", "syringe", "bandage", "thermometer", "heart"]),
        ("工作", ["briefcase", "pencil", "book", "graduationcap", "building", "phone", "envelope"]),
        ("其他", ["circle", "star", "heart", "diamond", "triangle", "square", "ellipsis"])
    ]
    
    var body: some View {
        NavigationView {
            List {
                ForEach(iconCategories, id: \.0) { category, icons in
                    Section(category) {
                        LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: 6), spacing: 16) {
                            ForEach(icons, id: \.self) { iconName in
                                Button {
                                    selectedIcon = iconName
                                    dismiss()
                                } label: {
                                    Image(systemName: iconName)
                                        .font(.title2)
                                        .foregroundColor(selectedIcon == iconName ? .white : .primary)
                                        .frame(width: 44, height: 44)
                                        .background(
                                            Circle()
                                                .fill(selectedIcon == iconName ? .blue : Color.gray.opacity(0.1))
                                        )
                                }
                                .buttonStyle(PlainButtonStyle())
                            }
                        }
                        .padding(.vertical, 8)
                    }
                }
            }
            .navigationTitle("选择图标")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button("完成") {
                        dismiss()
                    }
                }
            }
        }
    }
}

struct ColorPickerView: View {
    @Environment(\.dismiss) private var dismiss
    @Binding var selectedColor: String
    
    private let predefinedColors: [String] = [
        "#3B82F6", // 蓝色
        "#10B981", // 绿色
        "#8B5CF6", // 紫色
        "#F59E0B", // 黄色
        "#EF4444", // 红色
        "#EC4899", // 粉色
        "#06B6D4", // 青色
        "#84CC16", // 青绿色
        "#F97316", // 橙色
        "#6B7280", // 灰色
        "#1F2937", // 深灰色
        "#7C2D12", // 棕色
        "#BE123C", // 深红色
        "#9333EA", // 深紫色
        "#0891B2", // 深青色
        "#CA8A04"  // 深黄色
    ]
    
    var body: some View {
        NavigationView {
            VStack(spacing: 24) {
                Text("选择颜色")
                    .font(.headline)
                    .padding(.top)
                
                LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: 4), spacing: 20) {
                    ForEach(predefinedColors, id: \.self) { colorHex in
                        Button {
                            selectedColor = colorHex
                            dismiss()
                        } label: {
                            Circle()
                                .fill(Color(hex: colorHex))
                                .frame(width: 60, height: 60)
                                .overlay(
                                    Circle()
                                        .stroke(
                                            selectedColor == colorHex ? Color.primary : Color.clear,
                                            lineWidth: 3
                                        )
                                )
                                .scaleEffect(selectedColor == colorHex ? 1.1 : 1.0)
                                .animation(.spring(response: 0.3), value: selectedColor)
                        }
                        .buttonStyle(PlainButtonStyle())
                    }
                }
                .padding(.horizontal)
                
                Spacer()
            }
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button("完成") {
                        dismiss()
                    }
                }
            }
        }
    }
}

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