//
//  Untitled.swift
//  LotteryTracker
//
//  Created by aaa on 2026/1/22.
//

import SwiftUI
internal import CoreData

struct AddTicketView: View {
    @Environment(\.dismiss) private var dismiss
    @Environment(\.managedObjectContext) private var viewContext
    @Environment(\.colorScheme) private var colorScheme
    
    @StateObject private var viewModel = AddTicketViewModel()
    @FocusState private var focusedField: Field?
    
    enum Field {
        case numbers
        case amount
    }
    
    var body: some View {
        NavigationView {
            ZStack {
                // 背景
                backgroundColor
                    .ignoresSafeArea()
                
                ScrollView {
                    VStack(spacing: 24) {
                        // 彩票类型选择
                        LotteryTypePicker(selectedType: $viewModel.selectedType)
                            .padding(.horizontal)
                        
                        // 投注号码输入
                        numbersInputSection
                            .padding(.horizontal)
                        
                        // 金额输入
                        AmountInputView(
                            betCount: $viewModel.betCount,
                            amountPerBet: $viewModel.amountPerBet,
                            totalAmount: viewModel.totalAmount
                        )
                        .padding(.horizontal)
                        
                        // 购买日期选择（替换开奖日期）
                        purchaseDateSection
                            .padding(.horizontal)
                        
                        // 错误提示
                        if !viewModel.errorMessage.isEmpty {
                            errorMessageView
                                .padding(.horizontal)
                        }
                        
                        // 操作按钮
                        actionButtons
                            .padding(.horizontal)
                            .padding(.top, 20)
                    }
                    .padding(.vertical)
                }
            }
            .navigationTitle("添加彩票记录")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Button("取消") {
                        dismiss()
                    }
                }
                
                ToolbarItemGroup(placement: .keyboard) {
                    Spacer()
                    
                    Button("完成") {
                        focusedField = nil
                    }
                }
            }
            .onTapGesture {
                // 点击空白处隐藏键盘
                focusedField = nil
            }
        }
    }
    
    // MARK: - 组件
    
    // 背景颜色
    private var backgroundColor: Color {
        colorScheme == .dark ? Color(.systemGray6) : Color(.systemGray6).opacity(0.3)
    }
    
    // 投注号码输入
    private var numbersInputSection: some View {
        VStack(alignment: .leading, spacing: 12) {
            HStack {
                Text("投注号码")
                    .font(.headline)
                
                Spacer()
                
                Button("随机生成") {
                    viewModel.numbers = generateSampleNumbers(for: viewModel.selectedType)
                }
                .font(.caption)
                .foregroundColor(.blue)
            }
            
            VStack(alignment: .leading, spacing: 8) {
                Text("请输入号码，用空格或逗号分隔")
                    .font(.caption)
                    .foregroundColor(.secondary)
                
                TextEditor(text: $viewModel.numbers)
                    .font(.system(.body, design: .monospaced))
                    .frame(minHeight: 80)
                    .padding(8)
                    .background(Color(.systemBackground))
                    .cornerRadius(8)
                    .overlay(
                        RoundedRectangle(cornerRadius: 8)
                            .stroke(focusedField == .numbers ? Color.blue : Color.gray.opacity(0.3), lineWidth: 1)
                    )
                    .focused($focusedField, equals: .numbers)
                
                Text("例如：01 05 12 23 28 33 + 09")
                    .font(.caption2)
                    .foregroundColor(.secondary)
            }
        }
        .padding()
        .background(Color(.systemBackground))
        .cornerRadius(12)
        .shadow(color: Color.black.opacity(0.05), radius: 5, x: 0, y: 2)
    }
    
    // 购买日期选择
    private var purchaseDateSection: some View {
        VStack(alignment: .leading, spacing: 12) {
            HStack {
                Text("购买日期")
                    .font(.headline)
                
                Spacer()
                
                Button("今天") {
                    viewModel.purchaseDate = Date()
                }
                .font(.caption)
                .foregroundColor(.blue)
                
                Button("昨天") {
                    viewModel.purchaseDate = Calendar.current.date(byAdding: .day, value: -1, to: Date()) ?? Date()
                }
                .font(.caption)
                .foregroundColor(.blue)
            }
            
            DatePicker(
                "选择购买日期",
                selection: $viewModel.purchaseDate,
                in: Date().addingTimeInterval(-365 * 24 * 3600)...Date(), // 过去一年到现在
                displayedComponents: .date
            )
            .datePickerStyle(.graphical)
            .padding()
            .background(Color(.systemBackground))
            .cornerRadius(12)
            .shadow(color: Color.black.opacity(0.05), radius: 5, x: 0, y: 2)
            
            // 开奖信息显示（只读）
            HStack {
                Image(systemName: "calendar.badge.clock")
                    .foregroundColor(.blue)
                
                VStack(alignment: .leading, spacing: 4) {
                    Text("购买时间: \(viewModel.formattedPurchaseDate)")
                        .font(.subheadline)
                        .foregroundColor(.secondary)
                    
                    Text("预计开奖: \(viewModel.formattedDrawDate)")
                        .font(.subheadline)
                        .foregroundColor(.green)
                }
                
                Spacer()
                
                Text("\(daysUntilDraw)天后")
                    .font(.caption)
                    .padding(.horizontal, 8)
                    .padding(.vertical, 4)
                    .background(Color.blue.opacity(0.1))
                    .foregroundColor(.blue)
                    .cornerRadius(6)
            }
            .padding(.horizontal, 4)
        }
        .padding()
        .background(Color(.systemBackground))
        .cornerRadius(12)
        .shadow(color: Color.black.opacity(0.05), radius: 5, x: 0, y: 2)
    }
    
    // 错误提示
    private var errorMessageView: some View {
        HStack {
            Image(systemName: "exclamationmark.triangle.fill")
                .foregroundColor(.red)
            
            Text(viewModel.errorMessage)
                .font(.subheadline)
                .foregroundColor(.red)
            
            Spacer()
        }
        .padding()
        .background(Color.red.opacity(0.1))
        .cornerRadius(8)
    }
    
    // 操作按钮
    private var actionButtons: some View {
        VStack(spacing: 12) {
            // 保存按钮
            Button(action: saveTicket) {
                HStack {
                    Spacer()
                    
                    Image(systemName: "checkmark.circle.fill")
                    
                    Text("保存记录")
                        .font(.headline)
                    
                    Spacer()
                }
                .padding()
                .background(viewModel.isValid ? Color.blue : Color.gray)
                .foregroundColor(.white)
                .cornerRadius(12)
            }
            .disabled(!viewModel.isValid)
            
            // 测试数据按钮
            Button(action: {
                viewModel.fillSampleData()
            }) {
                HStack {
                    Spacer()
                    
                    Image(systemName: "wand.and.stars")
                    
                    Text("填充测试数据")
                        .font(.subheadline)
                    
                    Spacer()
                }
                .padding()
                .background(Color.green.opacity(0.1))
                .foregroundColor(.green)
                .cornerRadius(12)
            }
            
            // 重置按钮
            Button(action: {
                viewModel.resetForm()
            }) {
                HStack {
                    Spacer()
                    
                    Image(systemName: "arrow.counterclockwise")
                    
                    Text("重置表单")
                        .font(.subheadline)
                    
                    Spacer()
                }
                .padding()
                .background(Color.orange.opacity(0.1))
                .foregroundColor(.orange)
                .cornerRadius(12)
            }
        }
    }
    
    // MARK: - 计算属性
    
    // 距离开奖天数
    private var daysUntilDraw: Int {
        let calendar = Calendar.current
        let components = calendar.dateComponents([.day], from: viewModel.purchaseDate, to: viewModel.drawDate)
        return max(0, components.day ?? 0)
    }
    
    // MARK: - 方法
    
    // 保存彩票记录
    private func saveTicket() {
        if viewModel.saveTicket(context: viewContext) {
            print("✅ 保存成功，关闭添加页面")
            
            // 发送数据更新通知
            NotificationCenter.default.post(name: .ticketsUpdated, object: nil)
            
            dismiss()
        } else {
            print("❌ 保存失败")
        }
    }
    
    // 生成示例号码
    private func generateSampleNumbers(for type: LotteryType) -> String {
        switch type {
        case .doubleColorBall:
            let redBalls = (1...33).shuffled().prefix(6).map { String(format: "%02d", $0) }
            let blueBall = String(format: "%02d", Int.random(in: 1...16))
            return "\(redBalls.joined(separator: " ")) + \(blueBall)"
            
        case .superLotto:
            let frontBalls = (1...35).shuffled().prefix(5).map { String(format: "%02d", $0) }
            let backBalls = (1...12).shuffled().prefix(2).map { String(format: "%02d", $0) }
            return "\(frontBalls.joined(separator: " ")) + \(backBalls.joined(separator: " "))"
            
        case .welfare3D:
            let numbers = (0...9).shuffled().prefix(3).map { String($0) }
            return numbers.joined(separator: " ")
            
        case .sevenStar:
            let numbers = (0...9).shuffled().prefix(7).map { String($0) }
            return numbers.joined(separator: " ")
            
        case .other:
            return "随机号码"
        }
    }
}

// 预览
struct AddTicketView_Previews: PreviewProvider {
    static var previews: some View {
        AddTicketView()
            .environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
    }
}
