import SwiftUI
import Combine

struct LearningSessionView: View {
    let taskTitle: String
    let taskType: String
    let taskColor: Color

    @Environment(\.accessibilityReduceMotion) private var reduceMotion
    @State private var elapsed: TimeInterval = 0
    @State private var animatedProgress: CGFloat = 0
    @State private var isRunning = true
    @State private var isPaused = false
    @State private var showEndConfirm = false
    @State private var showCelebration = false
    @State private var sessionEnded = false
    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

    var body: some View {
        ZStack {
            Color.zxBg0.ignoresSafeArea()
            VStack(spacing: 0) {
                ScrollView {
                    VStack(spacing: 20) {
                        timerCard
                        sessionInfoCard
                        tipsCard
                    }
                    .padding(.horizontal, 20)
                    .padding(.top, 8)
                    .padding(.bottom, 120)
                }
                .scrollIndicators(.hidden)
            }
            VStack { Spacer()
                bottomBar
            }.ignoresSafeArea(edges: .bottom)
        }
        .navigationBarTitleDisplayMode(.inline).animatedTabBarHide()
        .toolbarBackground(.hidden, for: .navigationBar)
        .onReceive(timer) { _ in
            if isRunning { elapsed += 1 }
        }
        .confirmationDialog("结束学习？", isPresented: $showEndConfirm, titleVisibility: .visible) {
            Button("结束并保存", role: .destructive) { isRunning = false; sessionEnded = true; showCelebration = true }
            Button("继续学习", role: .cancel) {}
        }
        .overlay {
            if showCelebration {
                ZXCelebrationView(title: "学习完成", subtitle: "你已专注学习了 \(formatTime(elapsed))，继续保持！") {
                    withAnimation(.easeOut(duration: 0.3)) { showCelebration = false }
                }
            }
        }
    }

    private var timerCard: some View {
        VStack(spacing: 16) {
            ZStack {
                // Background track
                Circle()
                    .trim(from: 0, to: 1)
                    .stroke(Color.zxFill008, style: StrokeStyle(lineWidth: 8, lineCap: .round))
                    .rotationEffect(.degrees(-90))
                    .frame(width: 180, height: 180)
                // Animated progress
                Circle()
                    .trim(from: 0, to: animatedProgress)
                    .stroke(
                        AngularGradient(
                            colors: [Color.zxPurple, Color.zxAccent, Color.zxPurple],
                            center: .center
                        ),
                        style: StrokeStyle(lineWidth: 8, lineCap: .round)
                    )
                    .rotationEffect(.degrees(-90))
                    .frame(width: 180, height: 180)
                    .animation(reduceMotion ? nil : .easeInOut(duration: 0.5), value: animatedProgress)
                VStack(spacing: 4) {
                    Text(formatTime(elapsed))
                        .font(.system(size: 36, weight: .black))
                        .foregroundColor(Color.zxF0)
                        .tracking(-1)
                        .contentTransition(.numericText())
                    Text("已学习")
                        .font(.system(size: 13, weight: .medium))
                        .foregroundColor(Color.zxF04)
                }
            }
            .onChange(of: elapsed) { newElapsed in
                let pct = min(CGFloat(newElapsed) / 1800, 1)
                if reduceMotion { animatedProgress = pct }
                else { withAnimation(.easeInOut(duration: 0.5)) { animatedProgress = pct } }
            }
            HStack(spacing: 12) {
                Button {
                    if isRunning { isPaused = true; isRunning = false }
                    else { isPaused = false; isRunning = true }
                } label: {
                    Label(isRunning ? "暂停" : "继续", systemImage: isRunning ? "pause.fill" : "icon-play")
                        .font(.system(size: 14, weight: .bold))
                        .foregroundColor(.white)
                        .frame(maxWidth: .infinity).frame(height: 48)
                        .background(ZXGradient.brandPurple)
                        .clipShape(RoundedRectangle(cornerRadius: 14))
                }
                .zxPressable()
                .accessibilityLabel(isRunning ? "暂停学习" : "继续学习")
                Button { showEndConfirm = true } label: {
                    Label("结束", systemImage: "stop.fill")
                        .font(.system(size: 14, weight: .semibold))
                        .foregroundColor(Color.zxF05)
                        .frame(maxWidth: .infinity).frame(height: 48)
                        .background(Color.zxFill005)
                        .overlay(RoundedRectangle(cornerRadius: 14).stroke(Color.zxBorder008, lineWidth: 1))
                        .clipShape(RoundedRectangle(cornerRadius: 14))
                }
                .zxPressable()
                .accessibilityLabel("结束学习")
                .accessibilityHint("停止计时并保存本次学习记录")
            }
        }
        .padding(24)
        .background(ZXGradient.progressCard)
        .overlay(RoundedRectangle(cornerRadius: 24).stroke(Color(hex: "#7C6EFA", opacity: 0.15), lineWidth: 1))
        .clipShape(RoundedRectangle(cornerRadius: 24))
    }

    private var sessionInfoCard: some View {
        VStack(spacing: 0) {
            ZXSessionInfoRow(icon: "doc.text.fill", label: "当前任务", value: taskTitle, color: taskColor)
            ZXSessionDivider()
            ZXSessionInfoRow(icon: "tag.fill", label: "任务类型", value: taskType, color: taskColor)
            ZXSessionDivider()
            ZXSessionInfoRow(icon: "target", label: "建议时长", value: "30 分钟", color: Color(hex: "#7C6EFA"))
            ZXSessionDivider()
            ZXSessionInfoRow(icon: "chart.line.uptrend.xyaxis", label: "今日已学", value: "\(Int(elapsed / 60)) 分钟", color: Color.zxGreen)
        }
        .background(Color.zxFill003)
        .clipShape(RoundedRectangle(cornerRadius: 16))
        .overlay(RoundedRectangle(cornerRadius: 16).stroke(Color.zxBorder006, lineWidth: 1))
    }

    private var tipsCard: some View {
        VStack(alignment: .leading, spacing: 10) {
            HStack(spacing: 8) {
                Image(systemName: "lightbulb.fill").font(.system(size: 14)).foregroundColor(Color.zxYellow)
                Text("学习小贴士").font(.system(size: 13, weight: .bold)).foregroundColor(Color.zxF0)
            }
            Text("保持专注，25-30 分钟后休息 5 分钟能有效提升记忆效果。学习时尽量避免切换任务。")
                .zxFontScaled(size: 12).foregroundColor(Color.zxF04).lineSpacing(4)
        }
        .padding(16)
        .background(Color.zxFill004)
        .overlay(RoundedRectangle(cornerRadius: 16).stroke(Color.zxBorder006, lineWidth: 1))
        .clipShape(RoundedRectangle(cornerRadius: 16))
    }

    private var bottomBar: some View {
        HStack(spacing: 12) {
            if isRunning {
                HStack(spacing: 6) {
                    Circle().fill(Color.zxGreen).frame(width: 8, height: 8)
                    Text("学习中…").font(.system(size: 12, weight: .medium)).foregroundColor(Color.zxGreen)
                }
            } else if isPaused {
                HStack(spacing: 6) {
                    Circle().fill(Color.zxYellow).frame(width: 8, height: 8)
                    Text("已暂停").font(.system(size: 12, weight: .medium)).foregroundColor(Color.zxYellow)
                }
            }
            Spacer()
        }
        .padding(.horizontal, 24).padding(.vertical, 14)
        .background(.ultraThinMaterial)
        .background(Color.zxBg0.opacity(0.95))
        .overlay(alignment: .top) { Rectangle().fill(Color.zxBorder008).frame(height: 1) }
    }

    private func formatTime(_ t: TimeInterval) -> String {
        let m = Int(t) / 60, s = Int(t) % 60
        return String(format: "%02d:%02d", m, s)
    }
}

struct ZXSessionInfoRow: View {
    let icon: String; let label: String; let value: String; let color: Color
    var body: some View {
        HStack(spacing: 12) {
            Image(systemName: icon).font(.system(size: 16)).foregroundColor(color)
                .frame(width: 32, height: 32).background(color.opacity(0.12)).clipShape(RoundedRectangle(cornerRadius: 8))
            Text(label).font(.system(size: 13, weight: .medium)).foregroundColor(Color.zxF04)
            Spacer()
            Text(value).font(.system(size: 13, weight: .semibold)).foregroundColor(Color.zxF0).lineLimit(1)
        }.padding(.horizontal, 16).padding(.vertical, 14)
    }
}

struct ZXSessionDivider: View {
    var body: some View { Rectangle().fill(Color.zxBorder008).frame(height: 1).padding(.leading, 60) }
}
