import SwiftUI
import SwiftData
import AVFoundation

@available(iOS 13.0, *)
@MainActor
struct VoiceInputView: View {
    @Environment(\.dismiss) private var dismiss
    @Environment(\.modelContext) private var modelContext
    @Query private var categories: [ExpenseCategory]
    
    @StateObject private var audioRecorder = AudioRecorder()
    @StateObject private var networkService = NetworkService.shared
    
    @State private var recognizedText = ""
    @State private var showingManualEdit = false
    @State private var parsedAmount: Double?
    @State private var parsedTitle: String = ""
    @State private var suggestedCategory: ExpenseCategory?
    @State private var showingUploadAlert = false
    @State private var uploadMessage = ""
    @State private var audioURL: String?
    @State private var isAIParsing = false
    @State private var showingAIResults = false
    @State private var aiParsingResults: [ExpenseInfo] = []
    
    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: 40) {
                    Spacer()
                    
                    // 录音状态指示
                    VStack(spacing: 16) {
                        Text(audioRecorder.isRecording ? "正在录音..." : "点击开始录音")
                            .font(.title2)
                            .fontWeight(.medium)
                            .foregroundColor(.primary)
                        
                        if audioRecorder.isRecording {
                            Text(formatTime(audioRecorder.recordingTime))
                                .font(.title)
                                .fontWeight(.bold)
                                .foregroundColor(.blue)
                        }
                    }
                    
                    // 录音按钮
                    if !isAIParsing {
                        Button(action: toggleRecording) {
                            ZStack {
                                Circle()
                                    .fill(audioRecorder.isRecording ? Color.red : Color.blue)
                                    .frame(width: 120, height: 120)
                                    .shadow(color: audioRecorder.isRecording ? .red.opacity(0.3) : .blue.opacity(0.3), radius: 20, x: 0, y: 8)
                                
                                Image(systemName: audioRecorder.isRecording ? "stop.fill" : "mic.fill")
                                    .font(.system(size: 40))
                                    .foregroundColor(.white)
                            }
                        }
                        .scaleEffect(audioRecorder.isRecording ? 1.1 : 1.0)
                        .animation(.easeInOut(duration: 0.2), value: audioRecorder.isRecording)
                    }
                    
                    // AI解析状态
                    if isAIParsing {
                        AILoadingView()
                            .transition(.scale.combined(with: .opacity))
                    } else if !recognizedText.isEmpty {
                        VStack(alignment: .leading, spacing: 12) {
                            Text("处理完成")
                                .font(.headline)
                                .foregroundColor(.primary)
                            
                            Text(recognizedText)
                                .font(.body)
                                .padding(16)
                                .frame(maxWidth: .infinity, alignment: .leading)
                                .background(
                                    RoundedRectangle(cornerRadius: 12)
                                        .fill(.ultraThinMaterial)
                                        .stroke(Color.gray.opacity(0.3), lineWidth: 1)
                                )
                        }
                        .padding(.horizontal, 24)
                    }
                    
                    Spacer()
                    
                    // 操作按钮
                    HStack(spacing: 16) {
                        Button("取消") {
                            audioRecorder.stopRecording()
                            dismiss()
                        }
                        .font(.headline)
                        .foregroundColor(.secondary)
                        .frame(maxWidth: .infinity)
                        .padding(.vertical, 16)
                        .background(
                            RoundedRectangle(cornerRadius: 12)
                                .fill(.ultraThinMaterial)
                                .stroke(Color.gray.opacity(0.3), lineWidth: 1)
                        )
                        
                        if !recognizedText.isEmpty && !isAIParsing {
                            Button("查看AI解析结果") {
                                showingAIResults = true
                            }
                            .font(.headline)
                            .foregroundColor(.white)
                            .frame(maxWidth: .infinity)
                            .padding(.vertical, 16)
                            .background(
                                LinearGradient(
                                    gradient: Gradient(colors: [
                                        Color(red: 0.4, green: 0.5, blue: 0.9),
                                        Color(red: 0.46, green: 0.29, blue: 0.64)
                                    ]),
                                    startPoint: .topLeading,
                                    endPoint: .bottomTrailing
                                )
                            )
                            .clipShape(RoundedRectangle(cornerRadius: 12))
                        }
                    }
                    .padding(.horizontal, 24)
                    .padding(.bottom, 40)
                }
            }
            .navigationTitle("语音记账")
            .navigationBarTitleDisplayMode(.large)
            .toolbar {
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button("关闭") {
                        audioRecorder.stopRecording()
                        dismiss()
                    }
                }
            }
            .alert("提示", isPresented: $showingUploadAlert) {
                Button("确定") { }
            } message: {
                Text(uploadMessage)
            }
        }
        .onDisappear {
            audioRecorder.stopRecording()
        }
        .sheet(isPresented: $showingAIResults) {
            if !aiParsingResults.isEmpty {
                AIParsingResultView(
                    expenses: aiParsingResults,
                    onSave: {
                        dismiss()
                    }
                )
            }
        }
    }
    
    private func toggleRecording() {
        if audioRecorder.isRecording {
            stopRecordingAndUpload()
        } else {
            startRecording()
        }
    }
    
    private func startRecording() {
        guard audioRecorder.hasPermission else {
            uploadMessage = "需要麦克风权限才能录音"
            showingUploadAlert = true
            return
        }
        
        // 重置状态
        recognizedText = ""
        aiParsingResults = []
        isAIParsing = false
        
        audioRecorder.startRecording()
    }
    
    private func stopRecordingAndUpload() {
        audioRecorder.stopRecording()
        print("🎤 录音已停止")
        
        // Get the recorded file and upload it
        guard let recordingURL = audioRecorder.getRecordingURL() else {
            uploadMessage = "录音文件获取失败"
            showingUploadAlert = true
            return
        }
        
        print("📁 获取录音文件: \(recordingURL)")
        
        Task { @MainActor in
            print("📤 开始上传音频文件...")
            let uploadResult = await networkService.uploadAudioFile(at: recordingURL)
            
            switch uploadResult {
            case .success(let response):
                print("✅ 音频上传成功: \(response.url)")
                self.audioURL = response.url
                
                // Start AI parsing
                print("🚀 开始调用AI解析...")
                await parseAudioWithAI(audioURL: response.url)
                
                // Clean up old recordings
                self.audioRecorder.cleanupOldRecordings()
                
            case .failure(let error):
                print("❌ 音频上传失败: \(error)")
                self.uploadMessage = "上传失败: \(error.localizedDescription)"
                self.showingUploadAlert = true
            }
        }
    }
    
    private func parseVoiceInput() {
        // 简单的文本解析逻辑
        let text = recognizedText.lowercased()
        
        // 提取金额
        let amountRegex = try! NSRegularExpression(pattern: "\\d+(\\.\\d+)?", options: [])
        let amountMatches = amountRegex.matches(in: text, options: [], range: NSRange(text.startIndex..., in: text))
        
        if let match = amountMatches.first {
            let range = Range(match.range, in: text)!
            parsedAmount = Double(String(text[range]))
        }
        
        // 提取标题（移除金额和"元"字）
        parsedTitle = recognizedText
            .replacingOccurrences(of: "\\d+(\\.\\d+)?元?", with: "", options: .regularExpression)
            .trimmingCharacters(in: .whitespacesAndNewlines)
        
        // 根据关键词推荐分类
        suggestedCategory = suggestCategory(for: text)
    }
    
    private func suggestCategory(for text: String) -> ExpenseCategory? {
        let foodKeywords = ["午餐", "晚餐", "早餐", "咖啡", "奶茶", "吃", "餐", "饭"]
        let transportKeywords = ["打车", "地铁", "公交", "出租车", "滴滴", "交通"]
        let shoppingKeywords = ["买", "购物", "衣服", "鞋子", "包"]
        let entertainmentKeywords = ["电影", "游戏", "娱乐", "KTV"]
        
        if foodKeywords.contains(where: { text.contains($0) }) {
            return categories.first { $0.name == "餐饮" }
        } else if transportKeywords.contains(where: { text.contains($0) }) {
            return categories.first { $0.name == "交通" }
        } else if shoppingKeywords.contains(where: { text.contains($0) }) {
            return categories.first { $0.name == "购物" }
        } else if entertainmentKeywords.contains(where: { text.contains($0) }) {
            return categories.first { $0.name == "娱乐" }
        }
        
        return categories.first { $0.name == "其他" }
    }
    
    private func processVoiceInput() {
        parseVoiceInput()
        
        guard let amount = parsedAmount,
              let category = suggestedCategory else {
            showingManualEdit = true
            return
        }
        
        saveExpense(amount: amount, title: parsedTitle, category: category)
    }
    
    private func saveExpense(amount: Double, title: String, category: ExpenseCategory) {
        let newRecord = ExpenseRecord(
            amount: amount,
            title: title.isEmpty ? "语音记账" : title,
            category: category,
            timestamp: Date()
        )
        
        modelContext.insert(newRecord)
        
        do {
            try modelContext.save()
            dismiss()
        } catch {
            print("保存失败: \(error)")
        }
    }
    
    private func parseAudioWithAI(audioURL: String) async {
        isAIParsing = true
        print("🤖 开始AI解析，音频URL: \(audioURL)")
        
        // Prepare category data for AI
        let categoryInfo = categories.map { CategoryInfo(name: $0.name, iconName: $0.iconName) }
        print("📝 发送分类信息: \(categoryInfo)")
        
        let parseResult = await networkService.parseAudioWithAI(
            audioURL: audioURL,
            categories: categoryInfo
        )
        
        switch parseResult {
        case .success(let response):
            print("✅ AI解析成功: \(response)")
            aiParsingResults = response.expenses
            recognizedText = "AI成功解析出 \(response.expenses.count) 条记账信息"
            
        case .failure(let error):
            print("❌ AI解析失败: \(error)")
            recognizedText = "AI解析失败"
            uploadMessage = "AI解析失败: \(error.localizedDescription)"
            showingUploadAlert = true
        }
        
        isAIParsing = false
    }
    
    private func formatTime(_ seconds: Int) -> String {
        let minutes = seconds / 60
        let remainingSeconds = seconds % 60
        return String(format: "%02d:%02d", minutes, remainingSeconds)
    }
}

struct VoiceEditView: View {
    @Environment(\.dismiss) private var dismiss
    @Query private var categories: [ExpenseCategory]
    
    let recognizedText: String
    let onSave: (Double, String, ExpenseCategory) -> Void
    
    @State private var amount: String
    @State private var title: String
    @State private var selectedCategory: ExpenseCategory?
    
    init(recognizedText: String, parsedAmount: Double, parsedTitle: String, suggestedCategory: ExpenseCategory?, onSave: @escaping (Double, String, ExpenseCategory) -> Void) {
        self.recognizedText = recognizedText
        self.onSave = onSave
        _amount = State(initialValue: parsedAmount > 0 ? String(parsedAmount) : "")
        _title = State(initialValue: parsedTitle)
        _selectedCategory = State(initialValue: suggestedCategory)
    }
    
    var body: some View {
        NavigationView {
            Form {
                Section("语音识别结果") {
                    Text(recognizedText)
                        .foregroundColor(.secondary)
                }
                
                Section("编辑信息") {
                    TextField("金额", text: $amount)
                        .keyboardType(.decimalPad)
                    
                    TextField("标题", text: $title)
                }
                
                Section("选择分类") {
                    LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: 3), spacing: 12) {
                        ForEach(categories, id: \.id) { category in
                            VStack {
                                Image(systemName: category.iconName)
                                    .font(.title2)
                                    .foregroundColor(selectedCategory?.id == category.id ? .white : Color(hex: category.colorHex))
                                    .frame(width: 40, height: 40)
                                    .background(
                                        Circle()
                                            .fill(selectedCategory?.id == category.id ? Color(hex: category.colorHex) : Color(hex: category.colorHex).opacity(0.1))
                                    )
                                
                                Text(category.name)
                                    .font(.caption)
                            }
                            .onTapGesture {
                                selectedCategory = category
                            }
                        }
                    }
                    .padding(.vertical, 8)
                }
            }
            .navigationTitle("编辑记录")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Button("取消") {
                        dismiss()
                    }
                }
                
                ToolbarItem(placement: .navigationBarTrailing) {
                    Button("保存") {
                        saveRecord()
                    }
                    .disabled(!isValid)
                }
            }
        }
    }
    
    private var isValid: Bool {
        !amount.isEmpty && !title.isEmpty && selectedCategory != nil && Double(amount) != nil
    }
    
    private func saveRecord() {
        guard let amountValue = Double(amount),
              let category = selectedCategory else { return }
        
        onSave(amountValue, title, category)
        dismiss()
    }
}

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