import SwiftUI

struct ReviewCardView: View {
    @StateObject private var viewModel = ReviewViewModel()
    let cards: [ReviewCardItem] = [
        .init(question: "什么是偏差(Bias)和方差(Variance)的权衡？",
              answer: "偏差衡量模型预测与真实值的偏离程度，方差衡量模型在不同训练集上的预测波动。偏差-方差权衡指的是：简单模型偏差高方差低（欠拟合），复杂模型偏差低方差高（过拟合）。最佳模型需要在两者之间取得平衡。",
              source: "机器学习 · 偏差-方差权衡", count: 1, total: 8),
        .init(question: "梯度下降中学习率(learning rate)的作用是什么？",
              answer: "学习率控制每次参数更新的步长。太大的学习率会导致不收敛甚至发散；太小的学习率会导致收敛速度过慢。通常从较大值开始逐步衰减，或使用自适应学习率算法如Adam。",
              source: "机器学习 · 梯度下降优化", count: 2, total: 8),
        .init(question: "L1正则化和L2正则化有什么区别？",
              answer: "L1正则化(权重绝对值之和)倾向于产生稀疏解，可用于特征选择；L2正则化(权重平方和)倾向于让所有权重都接近零但不等於零，防止过拟合效果更好。",
              source: "机器学习 · 正则化方法", count: 3, total: 8),
    ]

    @Environment(\.accessibilityReduceMotion) private var reduceMotion
    @State private var idx = 0
    @State private var flipped = false
    @State private var rating: Int? = nil
    @State private var finish = false
    @State private var showCelebration = false

    var current: ReviewCardItem { cards[idx] }

    var body: some View {
        ZStack {
            Color.zxBg0.ignoresSafeArea()
            VStack(spacing: 0) {
                progressBar
                ScrollView {
                    VStack(spacing: 20) {
                        flashCard
                        if flipped { ratingBar }
                    }
                    .padding(.horizontal, 20)
                    .padding(.top, 12)
                    .padding(.bottom, 40)
                }
                .scrollIndicators(.hidden)
            }
        }
        .navigationBarTitleDisplayMode(.inline).animatedTabBarHide()
        .toolbarBackground(.hidden, for: .navigationBar)
        .task { await viewModel.loadDueCards() }
        .overlay {
            if showCelebration {
                ZXCelebrationView(title: "复习完成", subtitle: "你已完成本次间隔复习，继续保持！") {
                    withAnimation(.easeOut(duration: 0.3)) { showCelebration = false }
                }
            }
        }
    }

    private var progressBar: some View {
        VStack(spacing: 8) {
            HStack {
                Text("间隔复习 \(current.count)/\(current.total)")
                    .font(.system(size: 12, weight: .medium))
                    .foregroundColor(Color.zxF04)
                Spacer()
                Text("剩余 \(current.total - current.count + 1) 张")
                    .font(.system(size: 12, weight: .medium))
                    .foregroundColor(Color.zxPurple)
            }
            ZStack(alignment: .leading) {
                RoundedRectangle(cornerRadius: 2).fill(Color.zxFill008).frame(height: 3)
                RoundedRectangle(cornerRadius: 2)
                    .fill(ZXGradient.progressBar)
                    .frame(width: max(3, CGFloat(current.count) / CGFloat(current.total) * (UIScreen.main.bounds.width - 40)), height: 3)
                    .animation(.easeInOut(duration: 0.5), value: current.count)
            }
        }
        .padding(.horizontal, 20)
        .padding(.top, 8)
        .padding(.bottom, 4)
    }

    private var flashCard: some View {
        VStack(spacing: 0) {
            Text(flipped ? "答案" : "问题")
                .zxFontScaled(size: 10, weight: .bold)
                .foregroundColor(flipped ? Color.zxGreen : Color.zxAccent)
                .tracking(0.5)
                .padding(.horizontal, 10).padding(.vertical, 3)
                .background((flipped ? Color.zxGreen : Color.zxPurple).opacity(0.12))
                .clipShape(Capsule())
                .padding(.bottom, 16)

            Text(flipped ? current.answer : current.question)
                .zxFontScaled(size: flipped ? 14 : 16, weight: flipped ? .medium : .semibold)
                .foregroundColor(Color.zxF0)
                .lineSpacing(6)
                .multilineTextAlignment(.center)
                .frame(maxWidth: .infinity, alignment: .center)

            if flipped {
                VStack(spacing: 6) {
                    Rectangle().fill(Color.zxBorder008).frame(height: 1).padding(.vertical, 12)
                    HStack(spacing: 4) {
                        Image(systemName: "book.closed.fill").font(.system(size: 10)).foregroundColor(Color.zxF03)
                        Text(current.source).zxFontScaled(size: 11).foregroundColor(Color.zxF04)
                    }
                }
            } else {
                Text("点击翻转查看答案")
                    .zxFontScaled(size: 11)
                    .foregroundColor(Color.zxF03)
                    .padding(.top, 20)
            }
        }
        .padding(24)
        .frame(minHeight: 240)
        .background(flipped ? ZXGradient.progressCard : ZXGradient.thinkingCard)
        .overlay(RoundedRectangle(cornerRadius: 20).stroke((flipped ? Color.zxPurple : Color.zxAccent).opacity(0.15), lineWidth: 1))
        .clipShape(RoundedRectangle(cornerRadius: 20))
        .onTapGesture { if reduceMotion { flipped.toggle() } else { withAnimation(.easeInOut(duration: 0.4)) { flipped.toggle() } } }
        .zxPressable()
        .accessibilityElement(children: .combine)
        .accessibilityLabel(flipped ? "答案：\(current.answer)" : "问题：\(current.question)")
        .accessibilityHint(flipped ? "来源：\(current.source)" : "双击翻转查看答案")
        .accessibilityAddTraits(.isButton)
    }

    private var ratingBar: some View {
        VStack(spacing: 10) {
            Text("你的掌握程度？").font(.system(size: 13, weight: .semibold)).foregroundColor(Color.zxF04)
            HStack(spacing: 10) {
                ZXRatingBtn(label: "完全不会", color: Color.zxRed, selected: rating == 1) { rating = 1; nextCard() }
                ZXRatingBtn(label: "有点难", color: Color.zxOrange, selected: rating == 2) { rating = 2; nextCard() }
                ZXRatingBtn(label: "基本会", color: Color.zxYellow, selected: rating == 3) { rating = 3; nextCard() }
                ZXRatingBtn(label: "很简单", color: Color.zxGreen, selected: rating == 4) { rating = 4; nextCard() }
            }
            HStack(spacing: 4) {
                Image(systemName: "arrow.triangle.2.circlepath").font(.system(size: 10)).foregroundColor(Color.zxF03)
                Text("AI 会根据你的评分自动安排下次复习时间").font(.system(size: 10)).foregroundColor(Color.zxF03)
            }
        }
    }

    private func nextCard() {
        rating = nil
        flipped = false
        if idx < cards.count - 1 {
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) { idx += 1 }
        } else {
            finish = true
            showCelebration = true
        }
    }
}

struct ReviewCardItem {
    let question: String
    let answer: String
    let source: String
    let count: Int
    let total: Int
}

struct ZXRatingBtn: View {
    let label: String; let color: Color; let selected: Bool; let action: () -> Void
    var body: some View {
        Button(action: action) {
            VStack(spacing: 4) {
                Text(label).font(.system(size: 11, weight: selected ? .bold : .medium))
                    .foregroundColor(selected ? .white : color)
            }
            .frame(maxWidth: .infinity).frame(height: 56)
            .background(selected ? AnyView(color) : AnyView(Color.zxFill005))
            .clipShape(RoundedRectangle(cornerRadius: 14))
            .overlay {
                if !selected { RoundedRectangle(cornerRadius: 14).stroke(Color.zxBorder008, lineWidth: 1) }
            }
        }
        .zxPressable()
        .accessibilityLabel("\(label)")
        .accessibilityHint("将此卡片标记为\(label)")
    }
}
