import SwiftUI
import SwiftData
import UniformTypeIdentifiers

struct SettingsView: View {
    @Environment(\.modelContext) private var modelContext
    @Query private var categories: [ExpenseCategory]
    @Query private var expenseRecords: [ExpenseRecord]
    
    @StateObject private var currencyManager = CurrencyManager.shared
    @State private var showingCurrencySelector = false
    @State private var showingCategoryManager = false
    @State private var showingDataExport = false
    @State private var showingClearDataAlert = false
    @State private var showingShareSheet = false
    @State private var exportURL: URL?
    
    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) {
                        // 货币设置
                        currencySection
                        
                        // 分类管理
                        categorySection
                        
                        // 数据管理
                        dataManagementSection
                        
                        // 关于
                        aboutSection
                        
                        Spacer(minLength: 100)
                    }
                    .padding(.horizontal, 24)
                    .padding(.top, 20)
                }
            }
            .navigationTitle("设置")
            .navigationBarTitleDisplayMode(.large)
        }
        .sheet(isPresented: $showingCurrencySelector) {
            CurrencySelectorView(selectedCurrency: $currencyManager.selectedCurrency)
        }
        .sheet(isPresented: $showingCategoryManager) {
            CategoryManagerView()
        }
        .sheet(isPresented: $showingShareSheet) {
            if let url = exportURL {
                ShareSheet(activityItems: [url])
            }
        }
        .alert("清除所有数据", isPresented: $showingClearDataAlert) {
            Button("取消", role: .cancel) { }
            Button("确认清除", role: .destructive) {
                clearAllData()
            }
        } message: {
            Text("此操作将永久删除所有记账数据，无法恢复。您确定要继续吗？")
        }
    }
    
    private var currencySection: some View {
        VStack(alignment: .leading, spacing: 16) {
            HStack {
                Image(systemName: "dollarsign.circle")
                    .font(.title2)
                    .foregroundColor(.blue)
                
                Text("货币设置")
                    .font(.headline)
                    .foregroundColor(.primary)
            }
            
            Button(action: {
                showingCurrencySelector = true
            }) {
                HStack {
                    VStack(alignment: .leading, spacing: 4) {
                        Text("货币单位")
                            .font(.body)
                            .foregroundColor(.primary)
                        
                        Text("选择您使用的货币")
                            .font(.caption)
                            .foregroundColor(.secondary)
                    }
                    
                    Spacer()
                    
                    HStack(spacing: 8) {
                        Text("\(currencyManager.selectedCurrency.symbol) \(currencyManager.selectedCurrency.rawValue)")
                            .font(.body)
                            .foregroundColor(.secondary)
                        
                        Image(systemName: "chevron.right")
                            .font(.caption)
                            .foregroundColor(.secondary)
                    }
                }
                .padding(16)
                .background(
                    RoundedRectangle(cornerRadius: 12)
                        .fill(Color.white.opacity(0.8))
                )
            }
            .buttonStyle(PlainButtonStyle())
        }
        .padding(20)
        .background(
            RoundedRectangle(cornerRadius: 16)
                .fill(Color.white.opacity(0.8))
                .shadow(color: .black.opacity(0.1), radius: 8, x: 0, y: 4)
        )
    }
    
    private var categorySection: some View {
        VStack(alignment: .leading, spacing: 16) {
            HStack {
                Image(systemName: "tag.circle")
                    .font(.title2)
                    .foregroundColor(.purple)
                
                Text("分类管理")
                    .font(.headline)
                    .foregroundColor(.primary)
                
                Spacer()
                
                Button("管理") {
                    showingCategoryManager = true
                }
                .font(.body)
                .foregroundColor(.blue)
            }
            
            VStack(spacing: 8) {
                ForEach(categories.prefix(4), id: \.id) { category in
                    CategoryRowView(category: category)
                }
            }
        }
        .padding(20)
        .background(
            RoundedRectangle(cornerRadius: 16)
                .fill(Color.white.opacity(0.8))
                .shadow(color: .black.opacity(0.1), radius: 8, x: 0, y: 4)
        )
    }
    
    private var dataManagementSection: some View {
        VStack(alignment: .leading, spacing: 16) {
            HStack {
                Image(systemName: "externaldrive")
                    .font(.title2)
                    .foregroundColor(.green)
                
                Text("数据管理")
                    .font(.headline)
                    .foregroundColor(.primary)
            }
            
            VStack(spacing: 12) {
                // 导出数据按钮
                Button(action: {
                    exportData()
                }) {
                    HStack {
                        Image(systemName: "square.and.arrow.up")
                            .foregroundColor(.white)
                        
                        Text("导出 CSV 数据")
                            .font(.system(size: 16, weight: .medium))
                            .foregroundColor(.white)
                    }
                    .frame(maxWidth: .infinity)
                    .padding(.vertical, 16)
                    .background(
                        LinearGradient(
                            gradient: Gradient(colors: [
                                Color(red: 0.18, green: 0.8, blue: 0.44),
                                Color(red: 0.15, green: 0.68, blue: 0.38)
                            ]),
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        )
                    )
                    .clipShape(RoundedRectangle(cornerRadius: 12))
                    .shadow(color: Color(red: 0.18, green: 0.8, blue: 0.44).opacity(0.3), radius: 8, x: 0, y: 4)
                }
                
                // 清除数据按钮
                Button(action: {
                    showingClearDataAlert = true
                }) {
                    HStack {
                        Image(systemName: "trash")
                            .foregroundColor(.white)
                        
                        Text("清除所有数据")
                            .font(.system(size: 16, weight: .medium))
                            .foregroundColor(.white)
                    }
                    .frame(maxWidth: .infinity)
                    .padding(.vertical, 16)
                    .background(
                        LinearGradient(
                            gradient: Gradient(colors: [
                                Color(red: 1.0, green: 0.42, blue: 0.42),
                                Color(red: 0.93, green: 0.35, blue: 0.14)
                            ]),
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        )
                    )
                    .clipShape(RoundedRectangle(cornerRadius: 12))
                    .shadow(color: Color(red: 1.0, green: 0.42, blue: 0.42).opacity(0.3), radius: 8, x: 0, y: 4)
                }
            }
        }
        .padding(20)
        .background(
            RoundedRectangle(cornerRadius: 16)
                .fill(Color.white.opacity(0.8))
                .shadow(color: .black.opacity(0.1), radius: 8, x: 0, y: 4)
        )
    }
    
    private var aboutSection: some View {
        VStack(alignment: .leading, spacing: 16) {
            HStack {
                Image(systemName: "info.circle")
                    .font(.title2)
                    .foregroundColor(.gray)
                
                Text("关于")
                    .font(.headline)
                    .foregroundColor(.primary)
            }
            
            VStack(spacing: 8) {
                SettingRowView(
                    title: "版本",
                    subtitle: "语音记账 v1.0.0",
                    showChevron: false
                )
                
                SettingRowView(
                    title: "隐私政策",
                    subtitle: "查看我们的隐私条款",
                    showChevron: true
                ) {
                    // 打开隐私政策
                }
                
                SettingRowView(
                    title: "用户协议",
                    subtitle: "查看服务条款",
                    showChevron: true
                ) {
                    // 打开用户协议
                }
            }
        }
        .padding(20)
        .background(
            RoundedRectangle(cornerRadius: 16)
                .fill(Color.white.opacity(0.8))
                .shadow(color: .black.opacity(0.1), radius: 8, x: 0, y: 4)
        )
    }
    
    private func exportData() {
        let csvContent = generateCSVContent()
        
        let tempDirectory = FileManager.default.temporaryDirectory
        let fileName = "语音记账数据_\(DateFormatter.fileNameFormatter.string(from: Date())).csv"
        let fileURL = tempDirectory.appendingPathComponent(fileName)
        
        do {
            try csvContent.write(to: fileURL, atomically: true, encoding: .utf8)
            exportURL = fileURL
            showingShareSheet = true
        } catch {
            print("导出失败: \(error)")
        }
    }
    
    private func generateCSVContent() -> String {
        var csvRows = ["日期,时间,金额,分类,标题,备注"]
        
        let sortedRecords = expenseRecords.sorted(by: { $0.timestamp > $1.timestamp })
        
        for record in sortedRecords {
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd"
            let date = dateFormatter.string(from: record.timestamp)
            
            let timeFormatter = DateFormatter()
            timeFormatter.dateFormat = "HH:mm:ss"
            let time = timeFormatter.string(from: record.timestamp)
            
            let amount = CurrencyManager.shared.formatAmountWithDecimals(record.amount)
            let category = record.category.name
            let title = record.title.replacingOccurrences(of: "\"", with: "\"\"")
            let notes = "" // ExpenseRecord模型没有notes字段，使用空字符串
            
            let csvRow = "\"\(date)\",\"\(time)\",\"\(amount)\",\"\(category)\",\"\(title)\",\"\(notes)\""
            csvRows.append(csvRow)
        }
        
        return csvRows.joined(separator: "\n")
    }
    
    private func clearAllData() {
        do {
            // 删除所有记录
            for record in expenseRecords {
                modelContext.delete(record)
            }
            
            try modelContext.save()
        } catch {
            print("清除数据失败: \(error)")
        }
    }
}

struct CategoryRowView: View {
    let category: ExpenseCategory
    
    var body: some View {
        HStack(spacing: 12) {
            Image(systemName: category.iconName)
                .font(.body)
                .foregroundColor(Color(hex: category.colorHex))
                .frame(width: 32, height: 32)
                .background(
                    Circle()
                        .fill(Color(hex: category.colorHex).opacity(0.1))
                )
            
            Text(category.name)
                .font(.body)
                .foregroundColor(.primary)
            
            Spacer()
            
            Text("\(category.recordCount) 笔记录")
                .font(.caption)
                .foregroundColor(.secondary)
        }
        .padding(.vertical, 8)
    }
}

struct SettingRowView: View {
    let title: String
    let subtitle: String
    let showChevron: Bool
    let action: (() -> Void)?
    
    init(title: String, subtitle: String, showChevron: Bool, action: (() -> Void)? = nil) {
        self.title = title
        self.subtitle = subtitle
        self.showChevron = showChevron
        self.action = action
    }
    
    var body: some View {
        Button(action: {
            action?()
        }) {
            HStack {
                VStack(alignment: .leading, spacing: 4) {
                    Text(title)
                        .font(.body)
                        .foregroundColor(.primary)
                    
                    Text(subtitle)
                        .font(.caption)
                        .foregroundColor(.secondary)
                }
                
                Spacer()
                
                if showChevron {
                    Image(systemName: "chevron.right")
                        .font(.caption)
                        .foregroundColor(.secondary)
                }
            }
            .padding(.vertical, 8)
        }
        .buttonStyle(PlainButtonStyle())
        .disabled(action == nil)
    }
}

struct CurrencySelectorView: View {
    @Environment(\.dismiss) private var dismiss
    @Binding var selectedCurrency: Currency
    @State private var tempSelectedCurrency: Currency
    
    init(selectedCurrency: Binding<Currency>) {
        self._selectedCurrency = selectedCurrency
        self._tempSelectedCurrency = State(initialValue: selectedCurrency.wrappedValue)
    }
    
    var body: some View {
        NavigationView {
            VStack(spacing: 20) {
                ForEach(Currency.allCases, id: \.self) { currency in
                    CurrencyOptionView(
                        currency: currency,
                        isSelected: tempSelectedCurrency == currency
                    ) {
                        tempSelectedCurrency = currency
                    }
                }
                
                Spacer()
            }
            .padding(24)
            .navigationTitle("选择货币")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Button("取消") {
                        dismiss()
                    }
                }
                
                ToolbarItem(placement: .navigationBarTrailing) {
                                    Button("确定") {
                    CurrencyManager.shared.setCurrency(tempSelectedCurrency)
                    dismiss()
                }
                }
            }
        }
    }
}

struct CurrencyOptionView: View {
    let currency: Currency
    let isSelected: Bool
    let onTap: () -> Void
    
    var body: some View {
        Button(action: onTap) {
            HStack(spacing: 16) {
                Text(currency.symbol)
                    .font(.title2)
                    .frame(width: 40, height: 40)
                    .background(
                        Circle()
                            .fill(isSelected ? .blue : .gray.opacity(0.2))
                    )
                    .foregroundColor(isSelected ? .white : .primary)
                
                VStack(alignment: .leading, spacing: 4) {
                    Text(currency.rawValue)
                        .font(.body)
                        .foregroundColor(.primary)
                    
                    Text(currency.code)
                        .font(.caption)
                        .foregroundColor(.secondary)
                }
                
                Spacer()
                
                if isSelected {
                    Image(systemName: "checkmark")
                        .foregroundColor(.blue)
                }
            }
            .padding(16)
            .background(
                RoundedRectangle(cornerRadius: 12)
                    .fill(isSelected ? Color.blue.opacity(0.1) : Color.white.opacity(0.8))
                    .stroke(isSelected ? .blue : .clear, lineWidth: 2)
            )
        }
        .buttonStyle(PlainButtonStyle())
    }
}



// ShareSheet for sharing exported files
struct ShareSheet: UIViewControllerRepresentable {
    let activityItems: [Any]
    
    func makeUIViewController(context: Context) -> UIActivityViewController {
        let controller = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
        return controller
    }
    
    func updateUIViewController(_ uiViewController: UIActivityViewController, context: Context) {}
}

// DateFormatter extension for file naming
extension DateFormatter {
    static let fileNameFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyyMMdd_HHmmss"
        return formatter
    }()
}

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