//
//  DoubleColorBallCompoents.swift
//  LotteryTracker
//
//  Created by aaa on 2026/1/25.
//

import SwiftUI

struct DoubleColorBallSection: View {
    @Binding var numbers: String
    
    @State private var redNumbers: [Int] = []
    @State private var blueNumbers: [Int] = []
    @State private var betCount = 1
    @State private var selectedType = LotteryType.doubleColorBall
    
    
    var body: some View {
        VStack(alignment: .leading, spacing: 16) {
            // 头部标题
            SectionHeader(title: "选择号码", icon: "number.circle")
            
            // 红球选择区
            VStack(alignment: .leading, spacing: 12) {
                NumberSelectionGrid(
                    title: "红球区",
                    color: .red,
                    range: 1...33,
                    maxSelection: 6,
                    selectedNumbers: $redNumbers
                )
            }
            
            // 蓝球选择区
            VStack(alignment: .leading, spacing: 12) {
                NumberSelectionGrid(
                    title: "蓝球区",
                    color: .blue,
                    range: 1...16,
                    maxSelection: 1,
                    selectedNumbers: $blueNumbers
                )
            }
            
            // 快速操作栏
            QuickActionsBar(
                onRandom: generateRandomNumbers,
                onClear: clearAllNumbers
            )
            
            // 红球/蓝球已选显示
            if (!redNumbers.isEmpty || !blueNumbers.isEmpty) {
                SelectedNumbersView(
                    reds: redNumbers,
                    blues: blueNumbers,
                    maxCount: 7,
                    onClear: {
                        redNumbers.removeAll()
                        blueNumbers.removeAll()
                    }
                )
                
            }
        }
        .onChange(of: redNumbers) {
            updateNumbers()
        }
        .onChange(of: blueNumbers) {
            updateNumbers()
        }
    }
    
    // MARK: -方法
    private func generateRandomNumbers() {
        redNumbers = Array(Set((1...33).shuffled().prefix(6))).sorted()
        blueNumbers = [Int.random(in: 1...16)]
    }
    
    private func clearAllNumbers() {
        withAnimation {
            redNumbers.removeAll()
            blueNumbers.removeAll()
        }
    }
    
    private func updateNumbers() {
        let redStr = redNumbers.sorted().map { String(format: "%02d", $0) }.joined(separator: " ")
        let blueStr = blueNumbers.sorted().map { String(format: "%02d", $0) }.joined(separator: " ")
        numbers = "\(redStr) + \(blueStr)"
    }
}


// MARK: - 头部组件
struct SectionHeader: View {
    let title: String
    let icon: String
    
    var body: some View {
        HStack {
            Label(title, systemImage: icon)
                .font(.headline)
                .foregroundColor(.primary)
            
            Spacer()
            
            // 状态指示器
            Capsule()
                .fill(Color.green.opacity(0.1))
                .frame(width: 80, height: 24)
                .overlay(
                    HStack(spacing: 4) {
                        Circle()
                            .fill(Color.green)
                            .frame(width: 8, height: 8)
                        
                        Text("可选")
                            .font(.caption2)
                            .foregroundColor(.green)
                    }
                )
        }
    }
}


// MARK: - 数字选择网格
struct NumberSelectionGrid: View {
    let title: String
    let color: Color
    let range: ClosedRange<Int>
    let maxSelection: Int
    @Binding var selectedNumbers: [Int]
    
    private let columns = Array(repeating: GridItem(.flexible()), count: 10)
    
    var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            // 标题和计数
            HStack {
                Text(title)
                    .font(.subheadline)
                    .fontWeight(.semibold)
                    .foregroundColor(color)
                
                Spacer()
                
                Text("\(selectedNumbers.count)/\(maxSelection)")
                    .font(.caption)
                    .fontWeight(.medium)
                    .foregroundColor(.secondary)
                    .padding(.horizontal, 8)
                    .padding(.vertical, 2)
                    .background(
                        Capsule()
                            .fill(color.opacity(0.1))
                    )
            }
            .padding(.horizontal, 4)
            
            // 数字网格
            LazyVGrid(columns: columns, spacing: 10) {
                ForEach(range, id: \.self) { number in
                    NumberButton(
                        number: number,
                        color: color,
                        isSelected: selectedNumbers.contains(number),
                        isSelectable: selectedNumbers.count < maxSelection || selectedNumbers.contains(number)
                    ) {
                        toggleNumber(number)
                    }
                }
            }
        }
        .padding(16)
        .background(Color(.secondarySystemBackground))
        .cornerRadius(12)
        .overlay(
            RoundedRectangle(cornerRadius: 12)
                .stroke(color.opacity(0.2), lineWidth: 1)
        )
    }
    
    private func toggleNumber(_ number: Int) {
        withAnimation(.spring(response: 0.3)) {
            if selectedNumbers.contains(number) {
                selectedNumbers.removeAll { $0 == number }
            } else if selectedNumbers.count < maxSelection {
                selectedNumbers.append(number)
                // 触觉反馈
                let generator = UIImpactFeedbackGenerator(style: .light)
                generator.impactOccurred()
            }
        }
    }
}

// MARK: - 数字按钮
struct NumberButton: View {
    let number: Int
    let color: Color
    let isSelected: Bool
    let isSelectable: Bool
    let action: () -> Void
    
    @State private var isPressed = false
    
    var body: some View {
        Button(action: handleAction) {
            ZStack {
                // 背景圆圈
                Circle()
                    .fill(backgroundColor)
                    .frame(width: 32, height: 32)
                
                // 数字
                Text(String(format: "%02d", number))
                    .font(.system(size: 16, weight: .semibold, design: .rounded))
                    .foregroundColor(textColor)
                
                // 选中标记
                if isSelected {
                    Circle()
                        .stroke(color, lineWidth: 2)
                        .frame(width: 32, height: 32)
                    
                    Image(systemName: "checkmark.circle.fill")
                        .font(.system(size: 12))
                        .foregroundColor(color)
                        .background(Color.white)
                        .clipShape(Circle())
                        .offset(x: 16, y: -16)
                }
            }
        }
        .buttonStyle(PressableButtonStyle())
        .disabled(!isSelectable && !isSelected)
        .opacity(isSelectable || isSelected ? 1.0 : 0.4)
    }
    
    private func handleAction() {
        if isSelectable {
            action()
        } else {
            let generator = UINotificationFeedbackGenerator()
            generator.notificationOccurred(.warning)
        }
    }
    
    private var backgroundColor: Color {
        isSelected ? color.opacity(0.15) : Color(.systemBackground)
    }
    
    private var textColor: Color {
        isSelected ? color : .primary
    }
}

struct PressableButtonStyle: ButtonStyle {
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .scaleEffect(configuration.isPressed ? 0.95 : 1.0)
            .opacity(configuration.isPressed ? 0.9 : 1.0)
            .animation(.easeInOut(duration: 0.1), value: configuration.isPressed)
    }
}

// MARK: - 已选号码显示
struct SelectedNumbersView: View {
    let reds: [Int]
    let blues: [Int]
    let maxCount: Int
    let onClear: () -> Void
    
    var body: some View {
        HStack(spacing: 8) {
            // 标签
            Capsule()
                .fill(Color(.gray).opacity(0.1))
                .frame(width: 36, height: 28)
                .overlay(
                    Text("已选")
                        .font(.caption2)
                        .fontWeight(.medium)
                        .foregroundColor(Color(.black))
                )
            
            // 号码显示
            ScrollView(.horizontal, showsIndicators: false) {
                HStack(spacing: 6) {
                    ForEach(reds.sorted(), id: \.self) { number in
                        Text(String(format: "%02d", number))
                            .font(.system(size: 14, weight: .medium, design: .monospaced))
                            .frame(width: 28, height: 28)
                            .background(Color(.red).opacity(0.15))
                            .foregroundColor(Color(.red))
                            .clipShape(Circle())
                    }
                    
                    ForEach(blues.sorted(), id: \.self) { number in
                        Text(String(format: "%02d", number))
                            .font(.system(size: 14, weight: .medium, design: .monospaced))
                            .frame(width: 28, height: 28)
                            .background(Color(.blue).opacity(0.15))
                            .foregroundColor(Color(.blue))
                            .clipShape(Circle())
                    }
                }
            }
            
            Spacer()
            
            // 清空按钮
            if (!reds.isEmpty || !blues.isEmpty) {
                Button(action: {
                    withAnimation {
                        onClear()
                    }
                }) {
                    Image(systemName: "xmark.circle.fill")
                        .font(.system(size: 16))
                        .foregroundColor(.secondary)
                        .padding(4)
                }
            }
        }
        .padding(.horizontal, 16)
        .padding(.vertical, 12)
        .background(Color(.systemBackground))
        .cornerRadius(10)
        .shadow(color: Color.black.opacity(0.05), radius: 2, x: 0, y: 1)
    }
}

// MARK: - 快速操作栏
struct QuickActionsBar: View {
    let onRandom: () -> Void
    let onClear: () -> Void
    
    var body: some View {
        HStack(spacing: 12) {
            // 随机生成
            ActionButton(
                title: "随机一注",
                icon: "dice.fill",
                color: .purple,
                action: onRandom
            )
            
            // 清空全部
            ActionButton(
                title: "清空重选",
                icon: "trash",
                color: .gray,
                action: onClear
            )
        }
    }
}

struct ActionButton: View {
    let title: String
    let icon: String
    let color: Color
    let action: () -> Void
    
    var body: some View {
        Button(action: {
            action()
            let generator = UIImpactFeedbackGenerator(style: .light)
            generator.impactOccurred()
        }) {
            HStack(spacing: 6) {
                Image(systemName: icon)
                    .font(.system(size: 14))
                
                Text(title)
                    .font(.caption)
                    .fontWeight(.medium)
            }
            .padding(.horizontal, 16)
            .padding(.vertical, 10)
            .frame(maxWidth: .infinity)
            .background(color.opacity(0.1))
            .foregroundColor(color)
            .cornerRadius(10)
        }
    }
}


struct ChipButton: View {
    let title: String
    let isSelected: Bool
    let action: () -> Void
    
    var body: some View {
        Button(action: action) {
            Text(title)
                .font(.system(size: 14, weight: .medium))
                .padding(.horizontal, 16)
                .padding(.vertical, 8)
                .background(
                    Capsule()
                        .fill(isSelected ? Color.blue : Color.gray.opacity(0.1))
                )
                .foregroundColor(isSelected ? .white : .primary)
                .overlay(
                    Capsule()
                        .stroke(isSelected ? Color.blue : Color.gray.opacity(0.3), lineWidth: 1)
                )
        }
    }
}

