import SwiftUI
import SwiftData

struct HistoryView: View {
    @Environment(\.modelContext) private var modelContext
    @Query(sort: \ExpenseRecord.timestamp, order: .reverse) private var expenseRecords: [ExpenseRecord]
    @State private var searchText = ""
    @State private var showingFilter = false
    @State private var selectedCategory: ExpenseCategory?
    @State private var showingDeleteAlert = false
    @State private var recordToDelete: ExpenseRecord?
    @State private var isEditMode = false
    @State private var showingDeleteSuccess = false
    @State private var deletedRecordTitle = ""
    
    // 按日期分组的记录
    private var groupedRecords: [DateGroup] {
        let filtered = filteredRecords
        let grouped = Dictionary(grouping: filtered) { record in
            Calendar.current.startOfDay(for: record.timestamp)
        }
        
        return grouped.map { (date, records) in
            let totalAmount = records.reduce(0) { $0 + $1.amount }
            return DateGroup(
                date: date,
                records: records.sorted { $0.timestamp > $1.timestamp },
                totalAmount: totalAmount
            )
        }.sorted { $0.date > $1.date }
    }
    
    // 过滤后的记录
    private var filteredRecords: [ExpenseRecord] {
        var filtered = expenseRecords
        
        if !searchText.isEmpty {
            filtered = filtered.filter { record in
                record.title.localizedCaseInsensitiveContains(searchText) ||
                record.category.name.localizedCaseInsensitiveContains(searchText)
            }
        }
        
        if let selectedCategory = selectedCategory {
            filtered = filtered.filter { $0.category.id == selectedCategory.id }
        }
        
        return filtered
    }
    
    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()
                
                VStack(spacing: 0) {
                    // 搜索和筛选
                    searchAndFilterSection
                    
                    // 编辑模式提示
                    if isEditMode && !groupedRecords.isEmpty {
                        editModeHint
                    }
                    
                    // 记录列表
                    if groupedRecords.isEmpty {
                        emptyStateView
                    } else {
                        recordsList
                    }
                }
            }
            .navigationTitle(isEditMode ? "编辑历史" : "历史")
            .navigationBarTitleDisplayMode(.large)
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Button(isEditMode ? "完成" : "编辑") {
                        isEditMode.toggle()
                    }
                    .foregroundColor(.blue)
                }
                
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button(action: {
                        showingFilter = true
                    }) {
                        Image(systemName: "magnifyingglass")
                            .foregroundColor(.blue)
                    }
                }
            }
        }
        .sheet(isPresented: $showingFilter) {
            FilterView(selectedCategory: $selectedCategory)
        }
        .alert("删除记录", isPresented: $showingDeleteAlert) {
            Button("取消", role: .cancel) {
                recordToDelete = nil
            }
            Button("删除", role: .destructive) {
                deleteRecord()
            }
                 } message: {
             if let record = recordToDelete {
                 Text("确定要删除「\(record.title)」这条记录吗？此操作无法撤销。")
             }
         }
         .alert("删除成功", isPresented: $showingDeleteSuccess) {
             Button("确定") { }
         } message: {
             Text("已删除「\(deletedRecordTitle)」")
         }
    }
    
    private var searchAndFilterSection: some View {
        VStack(spacing: 16) {
            HStack(spacing: 12) {
                // 搜索框
                HStack {
                    Image(systemName: "magnifyingglass")
                        .foregroundColor(.secondary)
                    
                    TextField("搜索记录...", text: $searchText)
                        .textFieldStyle(PlainTextFieldStyle())
                }
                .padding(12)
                .background(
                    RoundedRectangle(cornerRadius: 12)
                        .fill(Color.white.opacity(0.8))
                        .stroke(Color.gray.opacity(0.3), lineWidth: 1)
                )
                
                // 筛选按钮
                Button(action: {
                    showingFilter = true
                }) {
                    Image(systemName: "line.3.horizontal.decrease.circle")
                        .font(.title2)
                        .foregroundColor(.blue)
                        .padding(12)
                        .background(
                            RoundedRectangle(cornerRadius: 12)
                                .fill(.blue.opacity(0.1))
                        )
                }
            }
            
            // 当前筛选状态
            if selectedCategory != nil || !searchText.isEmpty {
                HStack {
                    if let category = selectedCategory {
                        FilterChip(text: category.name) {
                            selectedCategory = nil
                        }
                    }
                    
                    if !searchText.isEmpty {
                        FilterChip(text: "搜索: \(searchText)") {
                            searchText = ""
                        }
                    }
                    
                    Spacer()
                }
            }
        }
        .padding(.horizontal, 24)
        .padding(.vertical, 16)
        .background(Color.white.opacity(0.8))
    }
    
    private var emptyStateView: some View {
        VStack(spacing: 20) {
            Spacer()
            
            Image(systemName: "list.bullet.clipboard")
                .font(.system(size: 60))
                .foregroundColor(.secondary)
            
            Text("暂无记录")
                .font(.title2)
                .fontWeight(.medium)
                .foregroundColor(.primary)
            
            Text("开始记账来查看历史记录")
                .font(.body)
                .foregroundColor(.secondary)
            
            Spacer()
        }
    }
    
    private var recordsList: some View {
        ScrollView {
            LazyVStack(spacing: 0, pinnedViews: [.sectionHeaders]) {
                ForEach(groupedRecords, id: \.date) { group in
                    Section {
                        VStack(spacing: 12) {
                            ForEach(group.records, id: \.id) { record in
                                ExpenseRecordRow(
                                    record: record,
                                    showDeleteButton: isEditMode,
                                    onDelete: {
                                        recordToDelete = record
                                        showingDeleteAlert = true
                                    }
                                )
                                .padding(.horizontal, 24)
                                .swipeActions(edge: .trailing, allowsFullSwipe: false) {
                                    Button("删除", role: .destructive) {
                                        recordToDelete = record
                                        showingDeleteAlert = true
                                    }
                                }
                            }
                        }
                        .padding(.vertical, 12)
                    } header: {
                        DateSectionHeader(group: group)
                    }
                }
            }
            
            Spacer(minLength: 100) // 为TabBar留空间
        }
    }
    
    private func deleteRecord() {
        guard let record = recordToDelete else { return }
        
        deletedRecordTitle = record.title
        modelContext.delete(record)
        
        do {
            try modelContext.save()
            showingDeleteSuccess = true
            
            // 如果删除后没有记录了，退出编辑模式
            if expenseRecords.isEmpty {
                isEditMode = false
            }
        } catch {
            print("删除记录失败: \(error)")
        }
        
        recordToDelete = nil
    }
    
    private var editModeHint: some View {
        HStack {
            Image(systemName: "info.circle")
                .foregroundColor(.blue)
            
            Text("点击删除按钮或向左滑动可删除记录")
                .font(.caption)
                .foregroundColor(.secondary)
            
            Spacer()
        }
        .padding(.horizontal, 24)
        .padding(.vertical, 8)
        .background(Color.blue.opacity(0.1))
    }
}

struct DateGroup {
    let date: Date
    let records: [ExpenseRecord]
    let totalAmount: Double
}

struct DateSectionHeader: View {
    let group: DateGroup
    
    private var dateFormatter: DateFormatter {
        let formatter = DateFormatter()
        let calendar = Calendar.current
        
        if calendar.isDateInToday(group.date) {
            return DateFormatter() // 会在下面设置
        } else if calendar.isDateInYesterday(group.date) {
            return DateFormatter() // 会在下面设置
        } else {
            formatter.dateFormat = "M月d日"
            return formatter
        }
    }
    
    private var dateText: String {
        let calendar = Calendar.current
        
        if calendar.isDateInToday(group.date) {
            return "今天"
        } else if calendar.isDateInYesterday(group.date) {
            return "昨天"
        } else {
            let formatter = DateFormatter()
            formatter.dateFormat = "M月d日"
            return formatter.string(from: group.date)
        }
    }
    
    private var weekdayText: String {
        let formatter = DateFormatter()
        formatter.dateFormat = "EEEE"
        formatter.locale = Locale(identifier: "zh_CN")
        return formatter.string(from: group.date)
    }
    
    var body: some View {
        HStack {
            VStack(alignment: .leading, spacing: 4) {
                Text(dateText)
                    .font(.system(size: 18, weight: .semibold))
                    .foregroundColor(.primary)
                
                if !Calendar.current.isDateInToday(group.date) && !Calendar.current.isDateInYesterday(group.date) {
                    Text(weekdayText)
                        .font(.caption)
                        .foregroundColor(.secondary)
                }
            }
            
            Spacer()
            
            VStack(alignment: .trailing, spacing: 4) {
                Text("¥ \(group.totalAmount, specifier: "%.2f")")
                    .font(.system(size: 18, weight: .bold))
                    .foregroundColor(.primary)
                
                Text("\(group.records.count)笔")
                    .font(.caption)
                    .foregroundColor(.secondary)
            }
        }
        .padding(.horizontal, 24)
        .padding(.vertical, 12)
        .background(Color.white.opacity(0.8))
    }
}

struct FilterChip: View {
    let text: String
    let onDelete: () -> Void
    
    var body: some View {
        HStack(spacing: 6) {
            Text(text)
                .font(.caption)
                .foregroundColor(.blue)
            
            Button(action: onDelete) {
                Image(systemName: "xmark.circle.fill")
                    .font(.caption)
                    .foregroundColor(.blue)
            }
        }
        .padding(.horizontal, 12)
        .padding(.vertical, 6)
        .background(
            RoundedRectangle(cornerRadius: 16)
                .fill(.blue.opacity(0.1))
                .stroke(.blue.opacity(0.3), lineWidth: 1)
        )
    }
}

struct FilterView: View {
    @Environment(\.dismiss) private var dismiss
    @Query private var categories: [ExpenseCategory]
    @Binding var selectedCategory: ExpenseCategory?
    
    var body: some View {
        NavigationView {
            VStack(alignment: .leading, spacing: 20) {
                Text("选择分类")
                    .font(.headline)
                    .foregroundColor(.primary)
                
                LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: 3), spacing: 16) {
                    // 全部分类选项
                    FilterCategoryItem(
                        name: "全部",
                        iconName: "list.bullet",
                        colorHex: "#6B7280",
                        isSelected: selectedCategory == nil
                    ) {
                        selectedCategory = nil
                        dismiss()
                    }
                    
                    // 具体分类选项
                    ForEach(categories, id: \.id) { category in
                        FilterCategoryItem(
                            name: category.name,
                            iconName: category.iconName,
                            colorHex: category.colorHex,
                            isSelected: selectedCategory?.id == category.id
                        ) {
                            selectedCategory = category
                            dismiss()
                        }
                    }
                }
                
                Spacer()
            }
            .padding(24)
            .navigationTitle("筛选")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button("关闭") {
                        dismiss()
                    }
                }
            }
        }
    }
}

struct FilterCategoryItem: View {
    let name: String
    let iconName: String
    let colorHex: String
    let isSelected: Bool
    let onTap: () -> Void
    
    var body: some View {
        VStack(spacing: 8) {
            Image(systemName: iconName)
                .font(.title2)
                .foregroundColor(isSelected ? .white : Color(hex: colorHex))
                .frame(width: 40, height: 40)
                .background(
                    Circle()
                        .fill(isSelected ? Color(hex: colorHex) : Color(hex: colorHex).opacity(0.1))
                )
            
            Text(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: colorHex) : Color.clear, lineWidth: 2)
        )
        .onTapGesture {
            onTap()
        }
    }
}

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