//
//  TicketDetailView.swift
//  LotteryTracker
//
//  Created by aaa on 2026/1/24.
//

import SwiftUI
internal import CoreData

struct TicketDetailView: View {
    @ObservedObject var ticket: LotteryTicket
    @Environment(\.dismiss) private var dismiss
    @Environment(\.managedObjectContext) private var context
    
    // 状态管理
    @State private var showingPrizeEditor = false
    @State private var isWinning: Bool = false
    @State private var prizeAmount: Float = 0
    @State private var animateBackground = false
    @State private var canResetToPending: Bool = false  // 缓存状态
    
    // 动画状态
    @State private var numberScale: [Bool] = []
    
    var body: some View {
        ZStack {
            // 动态背景
            LinearGradient(
                gradient: Gradient(colors: [
                    ticketColor.opacity(0.08),
                    .clear,
                    ticketColor.opacity(0.03)
                ]),
                startPoint: .topLeading,
                endPoint: .bottomTrailing
            )
            .ignoresSafeArea()
            .hueRotation(.degrees(animateBackground ? 10 : 0))
            .animation(
                Animation.easeInOut(duration: 4).repeatForever(autoreverses: true),
                value: animateBackground
            )
            .onAppear { animateBackground = true }
            
            ScrollView {
                VStack(spacing: 24) {
                    // 1. 顶部状态卡片
                    VStack(spacing: 20) {
                        // 票种图标与状态
                        HStack {
                            VStack(alignment: .leading, spacing: 4) {
                                Text(ticket.type ?? "彩票")
                                    .font(.title2)
                                    .fontWeight(.bold)
                                    .foregroundColor(.primary)
                                
                                Text(ticketStatusText)
                                    .font(.caption)
                                    .fontWeight(.medium)
                                    .padding(.horizontal, 8)
                                    .padding(.vertical, 4)
                                    .background(statusColor.opacity(0.2))
                                    .foregroundColor(statusColor)
                                    .clipShape(Capsule())
                            }
                            
                            Spacer()
                            
                            ZStack {
                                Circle()
                                    .fill(ticketColor.opacity(0.15))
                                    .frame(width: 70, height: 70)
                                
                                Image(systemName: ticketIconName)
                                    .font(.system(size: 32))
                                    .foregroundColor(ticketColor)
                                    .shadow(color: ticketColor.opacity(0.3), radius: 4)
                            }
                        }
                        
                        // 金额显示
                        VStack(spacing: 8) {
                            Text("投注金额")
                                .font(.caption)
                                .foregroundColor(.secondary)
                            
                            Text(Formatters.formatCurrency(ticket.amount))
                                .font(.system(size: 36, weight: .heavy, design: .rounded))
                                .foregroundColor(ticketColor)
                        }
                        .padding(.vertical, 12)
                        .frame(maxWidth: .infinity)
                        .background(
                            RoundedRectangle(cornerRadius: 16)
                                .fill(ticketColor.opacity(0.06))
                                .overlay(
                                    RoundedRectangle(cornerRadius: 16)
                                        .stroke(ticketColor.opacity(0.2), lineWidth: 1)
                                )
                        )
                    }
                    .padding()
                    .background(
                        RoundedRectangle(cornerRadius: 20)
                            .fill(.ultraThinMaterial)
                            .shadow(color: .black.opacity(0.05), radius: 10, y: 5)
                    )
                    .padding(.horizontal)
                    
                    // 2. 彩票号码 - 优化显示
                    VStack(alignment: .leading, spacing: 16) {
                        HStack {
                            Text("投注号码")
                                .font(.headline)
                            
                            Spacer()
                            
                            Text("共 \(ticket.numberArray.count) 个号码")
                                .font(.caption)
                                .foregroundColor(.secondary)
                        }
                        
                        // 智能网格布局：根据数量自动调整列数
                        LazyVGrid(
                            columns: Array(
                                repeating: GridItem(.flexible(), spacing: 10),
                                count: min(ticket.numberArray.count, 6) > 5 ? 6 : 5
                            ),
                            spacing: 12
                        ) {
                            ForEach(Array(ticket.numberArray.enumerated()), id: \.offset) { index, number in
                                NumberBall(number: number, index: index, color: ticketColor)
                            }
                        }
                    }
                    .padding()
                    .background(
                        RoundedRectangle(cornerRadius: 20)
                            .fill(.ultraThinMaterial)
                            .shadow(color: .black.opacity(0.05), radius: 10, y: 5)
                    )
                    .padding(.horizontal)
                    
                    // 3. 信息卡片
                    VStack(spacing: 0) {
                        InfoRow(
                            icon: "calendar",
                            title: "购买时间",
                            value: ticket.formattedDate,
                            iconColor: .blue
                        )
                        
                        Divider()
                            .padding(.horizontal)
                        
                        InfoRow(
                            icon: "clock",
                            title: "开奖时间",
                            value: ticket.formattedDrawDate,
                            iconColor: .orange
                        )
                        
                        if ticket.ticketStatus != .pending {
                            Divider()
                                .padding(.horizontal)
                            
                            InfoRow(
                                icon: "trophy",
                                title: "中奖状态",
                                value: ticket.ticketStatus == .won ? "已中奖" : "未中奖",
                                iconColor: ticket.ticketStatus == .won ? .yellow : .gray
                            )
                            
                            if ticket.ticketStatus == .won {
                                Divider()
                                    .padding(.horizontal)
                                
                                InfoRow(
                                    icon: "banknote",
                                    title: "中奖金额",
                                    value: Formatters.formatCurrency(ticket.prizeAmount),
                                    iconColor: .green
                                )
                                .foregroundColor(.green)
                            }
                        }
                    }
                    .padding()
                    .background(
                        RoundedRectangle(cornerRadius: 20)
                            .fill(.ultraThinMaterial)
                            .shadow(color: .black.opacity(0.05), radius: 10, y: 5)
                    )
                    .padding(.horizontal)
                    
                    // 4. 中奖管理按钮
                    if ticket.ticketStatus == .pending {
                        VStack(spacing: 16) {
                            Text("开奖结果管理")
                                .font(.headline)
                                .frame(maxWidth: .infinity, alignment: .leading)
                            
                            HStack(spacing: 12) {
                                 Button(action: { updateWinningStatus(isWinning: false) }) {
                                     HStack {
                                         Image(systemName: "xmark.circle")
                                         Text("未中奖")
                                     }
                                     .frame(maxWidth: .infinity)
                                     .padding(.vertical, 14)
                                     .background(Color.gray.opacity(0.15))
                                     .foregroundColor(.secondary)
                                     .clipShape(RoundedRectangle(cornerRadius: 14))
                                 }
                                
                                Button(action: { showingPrizeEditor = true }) {
                                    HStack {
                                        Image(systemName: "trophy")
                                        Text("设置中奖")
                                    }
                                    .frame(maxWidth: .infinity)
                                    .padding(.vertical, 14)
                                    .background(ticketColor.opacity(0.15))
                                    .foregroundColor(ticketColor)
                                    .clipShape(RoundedRectangle(cornerRadius: 14))
                                }
                            }
                        }
                        .padding()
                        .background(
                            RoundedRectangle(cornerRadius: 20)
                                .fill(.ultraThinMaterial)
                                .shadow(color: .black.opacity(0.05), radius: 10, y: 5)
                        )
                        .padding(.horizontal)
                    }
                }
                .padding(.vertical, 24)
            }
        }
        .navigationTitle("彩票详情")
        .navigationBarTitleDisplayMode(.inline)
        .toolbar {
            ToolbarItem(placement: .navigationBarTrailing) {
                Menu {
                    if canResetToPending {
                        Button(action: { resetToPending() }) {
                            Label("重置为待开奖", systemImage: "arrow.uturn.backward")
                        }
                    }
                    
                    Button(role: .destructive, action: deleteTicket) {
                        Label("删除彩票", systemImage: "trash")
                    }
                } label: {
                    Image(systemName: "ellipsis.circle")
                        .font(.system(size: 20))
                }
            }
        }
        .sheet(isPresented: $showingPrizeEditor) {
            PrizeEditorView(
                isPresented: $showingPrizeEditor,
                prizeAmount: $prizeAmount,
                onSave: { saveWinningStatus() }
            )
        }
        .onAppear {
            // 初始化状态
            isWinning = ticket.ticketStatus == .won
            prizeAmount = ticket.prizeAmount
            canResetToPending = ticket.ticketStatus != .pending
        }
        .onChange(of: ticket.ticketStatus) { oldValue, newValue in
            canResetToPending = newValue != .pending
        }
    }
    
    // MARK: - 辅助视图
    
    // 数字球组件
    struct NumberBall: View {
        let number: String
        let index: Int
        let color: Color
        @State private var isAnimated = false
        
        var body: some View {
            Text(number)
                .font(.system(size: 18, weight: .bold, design: .rounded))
                .frame(width: 50, height: 50)
                .background(
                    Circle()
                        .fill(color)
                        .shadow(color: color.opacity(0.4), radius: 3, y: 2)
                )
                .foregroundColor(.white)
                .scaleEffect(isAnimated ? 1 : 0.8)
                .opacity(isAnimated ? 1 : 0.5)
                .onAppear {
                    withAnimation(
                        .spring(response: 0.6, dampingFraction: 0.7)
                        .delay(Double(index) * 0.05)
                    ) {
                        isAnimated = true
                    }
                }
        }
    }
    
    // 信息行组件（增强版）
    struct InfoRow: View {
        let icon: String
        let title: String
        let value: String
        let iconColor: Color
        
        var body: some View {
            HStack(spacing: 16) {
                Image(systemName: icon)
                    .font(.system(size: 18))
                    .frame(width: 30)
                    .foregroundColor(iconColor)
                
                VStack(alignment: .leading, spacing: 2) {
                    Text(title)
                        .font(.caption)
                        .foregroundColor(.secondary)
                    
                    Text(value)
                        .font(.body)
                        .fontWeight(.medium)
                }
                
                Spacer()
            }
            .padding(.vertical, 12)
            .padding(.horizontal)
        }
    }
    
    // MARK: - 业务逻辑
    
    private var ticketStatusText: String {
        switch ticket.ticketStatus {
        case .pending:
            return "待开奖"
        case .won:
            return "已中奖"
        case .lost:
            return "未中奖"
        }
    }
    
    private var statusColor: Color {
        switch ticket.ticketStatus {
        case .pending:
            return .orange
        case .won:
            return .green
        case .lost:
            return .gray
        }
    }
    
    private var ticketIconName: String {
        switch ticket.lotteryType {
        case .doubleColorBall:
            return "circle.grid.2x2.fill"
        case .superLotto:
            return "star.circle.fill"
        case .happy8:
            return "8.circle.fill"
        case .sevenStar:
            return "7.circle.fill"
        case .other:
            return "ticket.fill"
        }
    }
    
    private var ticketColor: Color {
        switch ticket.lotteryType {
        case .doubleColorBall: return Color(red: 0.9, green: 0.2, blue: 0.2)    // 红色
        case .superLotto: return Color(red: 0.2, green: 0.4, blue: 0.9)         // 蓝色
        case .happy8: return Color(red: 0.7, green: 0.2, blue: 0.8)             // 紫色
        case .sevenStar: return Color(red: 0.2, green: 0.7, blue: 0.4)          // 绿色
        case .other: return Color(red: 1.0, green: 0.5, blue: 0.7)              // 粉色
        }
    }
    
    private func updateWinningStatus(isWinning: Bool) {
        if isWinning {
            showingPrizeEditor = true
        } else {
            ticket.ticketStatus = .lost
            ticket.prizeAmount = 0
            saveChanges()  // 这里会发送通知
        }
    }
    
    private func saveWinningStatus() {
        ticket.ticketStatus = .won
        ticket.prizeAmount = prizeAmount
        // prizeAmount 已经在 PrizeEditorView 中通过绑定更新了
        saveChanges()  // 这里会发送通知
        showingPrizeEditor = false
    }
    
    private func resetToPending() {
        ticket.ticketStatus = .pending
        ticket.prizeAmount = 0
        saveChanges()  // 这里会发送通知
    }
    
    private func saveChanges() {
        do {
            try context.save()
            
            // 发送数据更新通知
            NotificationCenter.default.post(name: .ticketsUpdated, object: nil)
            
//            // 添加保存成功的视觉反馈
//            let feedback = UINotificationFeedbackGenerator()
//            feedback.notificationOccurred(.success)
//            print("✅ 彩票状态已更新并发送通知")
        } catch {
            print("保存失败: \(error)")
        }
    }
    
    private func deleteTicket() {
        context.delete(ticket)
        do {
            try context.save()
            dismiss()
        } catch {
            print("删除失败: \(error)")
        }
    }
}

// MARK: - 中奖金额编辑器视图
struct PrizeEditorView: View {
    @Binding var isPresented: Bool
    @Binding var prizeAmount: Float
    let onSave: () -> Void
    
    @State private var amountText: String = ""
    @FocusState private var isInputFocused: Bool
    
    var body: some View {
        NavigationView {
            VStack(spacing: 30) {
                Image(systemName: "trophy.fill")
                    .font(.system(size: 70))
                    .foregroundColor(.yellow)
                    .padding()
                    .background(
                        Circle()
                            .fill(.yellow.opacity(0.15))
                    )
                
                VStack(spacing: 8) {
                    Text("中奖金额")
                        .font(.title2)
                        .fontWeight(.bold)
                    
                    Text("请输入您的中奖金额")
                        .font(.body)
                        .foregroundColor(.secondary)
                }
                
                // 金额输入
                VStack(spacing: 20) {
                    HStack(alignment: .firstTextBaseline) {
                        TextField(Formatters.formatCurrency(0), text: $amountText)
                            .font(.system(size: 48, weight: .bold, design: .rounded))
                            .keyboardType(.decimalPad)
                            .multilineTextAlignment(.center)
                            .focused($isInputFocused)
                            .onChange(of: amountText) { oldValue, newValue in
                                // 格式化输入，只允许数字和小数点
                                let filtered = newValue.filter { "0123456789.".contains($0) }
                                let components = filtered.split(separator: ".")
                                if components.count > 2 {
                                    // 多于一个小数点，去掉多余的
                                    amountText = String(filtered.dropLast())
                                } else if components.count == 2 && components[1].count > 2 {
                                    // 小数部分超过2位
                                    amountText = String(filtered.dropLast())
                                } else {
                                    amountText = filtered
                                }
                                
                                // 更新绑定的金额
                                prizeAmount = Float(amountText) ?? 0
                            }
                    }
                    
                    // 快捷金额按钮
                    VStack(spacing: 12) {
                        Text("快捷金额")
                            .font(.caption)
                            .foregroundColor(.secondary)
                        
                        LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: 4), spacing: 12) {
                            ForEach([5, 10, 20, 50], id: \.self) { amount in
                                Button(action: {
                                    prizeAmount = Float(amount)
                                    amountText = String(format: "%.0f", prizeAmount)
                                }) {
                                    Text(Formatters.formatCurrency(Float(amount)))
                                        .font(.system(size: 14, weight: .medium))
                                        .padding(.vertical, 8)
                                        .frame(maxWidth: .infinity)
                                        .background(Color.green.opacity(0.1))
                                        .foregroundColor(.green)
                                        .clipShape(Capsule())
                                }
                            }
                        }
                    }
                }
                .padding(.horizontal, 40)
                
                Spacer()
                
                Button(action: {
                    onSave()
                    isPresented = false
                }) {
                    Text("确认保存")
                        .font(.headline)
                        .foregroundColor(.white)
                        .frame(maxWidth: .infinity)
                        .padding(.vertical, 16)
                        .background(Color.green)
                        .clipShape(RoundedRectangle(cornerRadius: 16))
                }
                .padding(.horizontal, 20)
                .padding(.bottom, 10)
                .disabled(prizeAmount <= 0)
                .opacity(prizeAmount <= 0 ? 0.6 : 1)
            }
            .padding()
            .navigationTitle("设置中奖金额")
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Button("取消") {
                        isPresented = false
                    }
                }
                
                ToolbarItemGroup(placement: .keyboard) {
                    Spacer()
                    Button("完成") {
                        isInputFocused = false
                    }
                }
            }
            .onAppear {
                // 初始化输入框内容
                amountText = prizeAmount > 0 ? Formatters.formatCurrency(prizeAmount) : ""
                isInputFocused = true
            }
        }
    }
}

