//
//  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()
    
    var body: some View {
        NavigationView {
            ZStack {
                // 背景
                backgroundColor
                    .ignoresSafeArea()
                
                ScrollView {
                    VStack(spacing: 24) {
                        // 彩票类型选择
                        LotteryTypePicker(selectedType: $viewModel.selectedType)
                            .padding(.horizontal)
                        
                        // 投注号码输入
                        TicketInputView(
                            selectedType: $viewModel.selectedType,
                            numbers: $viewModel.numbers,
                            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()
                    }
                }
            }
        }
    }
    
    // MARK: - 组件
    
    // 背景颜色
    private var backgroundColor: Color {
        colorScheme == .dark ? Color(.systemGray6) : Color(.systemGray6).opacity(0.3)
    }
    
    // 购买日期选择
    private var purchaseDateSection: some View {
        VStack(alignment: .leading, spacing: 12) {
            Text("购买日期")
                .font(.headline)
            VStack {
                HStack {
                    Label {
                        Text("点按日期进行选择")
                    } icon: {
                        Image(systemName: "hand.tap")
                    }
                    .font(.caption)
                    .foregroundColor(.blue.opacity(0.7))
                    
                    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()
                .cornerRadius(12)
                .shadow(color: Color.black.opacity(0.05), radius: 5, x: 0, y: 2)
                .background(
                    Color(uiColor: UIColor { traitCollection in
                        return traitCollection.userInterfaceStyle == .dark ?
                        UIColor(red: 0.15, green: 0.15, blue: 0.17, alpha: 1.0) : // 深色模式
                        UIColor(red: 0.98, green: 0.97, blue: 0.95, alpha: 1.0)  // 浅色模式
                    })
                )
                
                // 开奖信息显示（只读）
                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: String {
        let calendar = Calendar.current
        let components = calendar.dateComponents([.day], from: viewModel.purchaseDate, to: viewModel.drawDate)
        let leftDays = max(0, components.day ?? 0)
        return leftDays == 0 ? "今天" : String(leftDays) + "天后"
    }
    
    // MARK: - 方法
    
    // 保存彩票记录
    private func saveTicket() {
        if viewModel.saveTicket(context: viewContext) {
            print("✅ 保存成功，关闭添加页面")
            
            // 发送数据更新通知
            NotificationCenter.default.post(name: .ticketsUpdated, object: nil)
            
            dismiss()
        } else {
            print("❌ 保存失败")
        }
    }
}

