import SwiftUI

struct StudyHomeView: View {
    @Binding var selectedTab: String
    @StateObject private var vm = StudyHomeViewModel()

    var body: some View {
        ZStack {
            Color.zxCanvas.ignoresSafeArea()

            switch vm.loadingState {
            case .idle, .loading:
                loadingView
            case .error(let msg):
                errorView(msg)
            case .loaded:
                contentView
            }
        }
        .task { await vm.loadAll() }
    }

    // MARK: - Loading / Error

    private var loadingView: some View {
        ProgressView()
            .tint(Color.zxPrimary)
            .frame(maxWidth: .infinity, maxHeight: .infinity)
    }

    private func errorView(_ msg: String) -> some View {
        VStack(spacing: 16) {
            Image(systemName: "exclamationmark.triangle")
                .font(.system(size: 40)).foregroundColor(Color.zxF03)
            Text(msg)
                .font(.system(size: 14)).foregroundColor(Color.zxF04)
                .multilineTextAlignment(.center)
            Button {
                Task { await vm.loadAll() }
            } label: {
                Text("重试")
                    .font(.system(size: 14, weight: .semibold))
                    .foregroundColor(.white)
                    .frame(height: 44).padding(.horizontal, 32)
                    .background(ZXGradient.brand)
                    .clipShape(RoundedRectangle(cornerRadius: ZXRadius.md))
            }
        }
        .padding(.horizontal, 40)
        .frame(maxWidth: .infinity, maxHeight: .infinity)
    }

    // MARK: - Content

    private var contentView: some View {
        ScrollView {
            VStack(spacing: 16) {
                streakHeader
                    .padding(.horizontal, 20).padding(.top, 8).padding(.bottom, 4)

                if let banner = vm.banner {
                    statusBanner(banner).padding(.horizontal, 20)
                }

                mainActionCard.padding(.horizontal, 20)

                if vm.todayReviewCount > 0 && !isReviewMainAction {
                    todayReviewSmallCard.padding(.horizontal, 20)
                }

                if vm.availableQuizCount > 0 && !isSelfTestMainAction {
                    selfTestSmallCard.padding(.horizontal, 20)
                }

                weeklySummaryCard.padding(.horizontal, 20)

                viewAnalysisLink

                Color.clear.frame(height: 100)
            }
        }
        .scrollIndicators(.hidden)
        .refreshable { await vm.refresh() }
    }

    // MARK: - Streak Header

    private var streakHeader: some View {
        HStack {
            Spacer()
            HStack(spacing: 4) {
                Image("icon-flame")
                    .font(.system(size: 14)).foregroundColor(Color.zxOrange)
                Text("\(vm.streakDays) 天连续")
                    .font(.system(size: 14, weight: .bold)).foregroundColor(Color.zxOrange)
            }
            .padding(.horizontal, 12).padding(.vertical, 6)
            .background(Color.zxOrangeBG(0.1))
            .clipShape(Capsule())
            .overlay(Capsule().stroke(Color(hex: "#F97316", opacity: 0.2), lineWidth: 1))
        }
    }

    // MARK: - Status Banner

    private func statusBanner(_ text: String) -> some View {
        HStack(spacing: 8) {
            Image(systemName: "info.circle")
                .font(.system(size: 14)).foregroundColor(Color.zxPrimary)
            Text(text)
                .font(.system(size: 14)).foregroundColor(Color.zxInkSecondary)
        }
        .padding(.horizontal, 16).padding(.vertical, 10)
        .frame(maxWidth: .infinity, alignment: .leading)
        .background(Color.zxPrimarySoft)
        .clipShape(RoundedRectangle(cornerRadius: ZXRadius.md))
    }

    // MARK: - Main Action Card

    @ViewBuilder
    private var mainActionCard: some View {
        switch vm.mainAction {
        case .continueSession(let kbTitle, let elapsed):
            actionCard(
                title: "继续上次学习",
                subtitle: "《\(kbTitle)》· \(elapsed)",
                icon: "arrow.triangle.2.circlepath",
                color: Color.zxPurple,
                cta: "继续学习",
                route: .learningSession(taskTitle: "继续学习", taskType: "study", taskColorHex: "#3D7FFB")
            )
        case .todaysReview(let count, let minutes):
            actionCard(
                title: "今日复习",
                subtitle: "\(count) 张卡片待复习 · 约 \(minutes) 分钟",
                icon: "arrow.triangle.2.circlepath",
                color: Color.zxPurple,
                cta: "开始复习",
                route: .reviewCard
            )
        case .selfTest(let quizId, let count):
            actionCard(
                title: "资料自测",
                subtitle: "有 \(count) 个自测题可作答",
                icon: "list.clipboard",
                color: Color.zxOrange,
                cta: "开始自测",
                route: .quizTake(quizId: quizId)
            )
        case .startLearning(let kbId, let count):
            tabSwitchCard(
                title: "开始学习",
                subtitle: "从 \(count) 个知识库中选择内容开始学习",
                icon: "sparkles",
                color: Color.zxPrimary,
                cta: "选择知识库",
                targetTab: "library"
            )
        case .empty:
            emptyStateCard
        case .none:
            EmptyView()
        }
    }

    private func actionCard(
        title: String,
        subtitle: String,
        icon: String,
        color: Color,
        cta: String,
        route: Route
    ) -> some View {
        NavigationLink(value: route) {
            VStack(spacing: 16) {
                HStack(alignment: .top) {
                    VStack(alignment: .leading, spacing: 6) {
                        Text("今日主行动")
                            .font(.system(size: 10, weight: .semibold))
                            .foregroundColor(Color.zxInkTertiary)
                            .textCase(.uppercase)
                            .tracking(0.5)
                        Text(title)
                            .font(.system(size: 24, weight: .heavy))
                            .foregroundColor(Color.zxF0)
                            .tracking(-0.5)
                        Text(subtitle)
                            .font(.system(size: 14))
                            .foregroundColor(Color.zxF04)
                    }
                    Spacer()
                    ZStack {
                        Circle()
                            .fill(color.opacity(0.12))
                            .frame(width: 64, height: 64)
                        Image(systemName: icon)
                            .font(.system(size: 26))
                            .foregroundColor(color)
                    }
                }
                HStack(spacing: 8) {
                    Text(cta)
                        .font(.system(size: 16, weight: .semibold))
                    Image(systemName: "arrow.right")
                        .font(.system(size: 14, weight: .bold))
                }
                .foregroundColor(Color.zxOnPrimary)
                .frame(maxWidth: .infinity).frame(height: 44)
                .background(ZXGradient.brand)
                .clipShape(RoundedRectangle(cornerRadius: 12))
            }
            .padding(20)
            .background(Color.zxSurfaceElevated)
            .overlay(RoundedRectangle(cornerRadius: 20).stroke(Color.zxHairline, lineWidth: 0.5))
            .clipShape(RoundedRectangle(cornerRadius: 20))
        }
        .foregroundColor(.primary)
    }

    // MARK: - Tab Switch Card

    private func tabSwitchCard(
        title: String,
        subtitle: String,
        icon: String,
        color: Color,
        cta: String,
        targetTab: String
    ) -> some View {
        Button {
            selectedTab = targetTab
        } label: {
            VStack(spacing: 16) {
                HStack(alignment: .top) {
                    VStack(alignment: .leading, spacing: 6) {
                        Text("今日主行动")
                            .font(.system(size: 10, weight: .semibold))
                            .foregroundColor(Color.zxInkTertiary)
                            .textCase(.uppercase)
                            .tracking(0.5)
                        Text(title)
                            .font(.system(size: 24, weight: .heavy))
                            .foregroundColor(Color.zxF0)
                            .tracking(-0.5)
                        Text(subtitle)
                            .font(.system(size: 14))
                            .foregroundColor(Color.zxF04)
                    }
                    Spacer()
                    ZStack {
                        Circle()
                            .fill(color.opacity(0.12))
                            .frame(width: 64, height: 64)
                        Image(systemName: icon)
                            .font(.system(size: 26))
                            .foregroundColor(color)
                    }
                }
                HStack(spacing: 8) {
                    Text(cta)
                        .font(.system(size: 16, weight: .semibold))
                    Image(systemName: "arrow.right")
                        .font(.system(size: 14, weight: .bold))
                }
                .foregroundColor(Color.zxOnPrimary)
                .frame(maxWidth: .infinity).frame(height: 44)
                .background(ZXGradient.brand)
                .clipShape(RoundedRectangle(cornerRadius: 12))
            }
            .padding(20)
            .background(Color.zxSurfaceElevated)
            .overlay(RoundedRectangle(cornerRadius: 20).stroke(Color.zxHairline, lineWidth: 0.5))
            .clipShape(RoundedRectangle(cornerRadius: 20))
        }
        .foregroundColor(.primary)
    }

    // MARK: - Empty State

    private var emptyStateCard: some View {
        VStack(spacing: 16) {
            HStack(alignment: .top) {
                VStack(alignment: .leading, spacing: 6) {
                    Text("今日主行动")
                        .font(.system(size: 10, weight: .semibold))
                        .foregroundColor(Color.zxInkTertiary)
                        .textCase(.uppercase)
                        .tracking(0.5)
                    Text("欢迎使用知习")
                        .font(.system(size: 24, weight: .heavy))
                        .foregroundColor(Color.zxF0)
                        .tracking(-0.5)
                    Text("导入学习资料，开启你的学习之旅")
                        .font(.system(size: 14))
                        .foregroundColor(Color.zxF04)
                }
                Spacer()
                ZStack {
                    Circle()
                        .fill(Color.zxPrimary.opacity(0.12))
                        .frame(width: 64, height: 64)
                    Image("icon-brain")
                        .font(.system(size: 26))
                        .foregroundColor(Color.zxPrimary)
                }
            }
            HStack(spacing: 12) {
                Button {
                    selectedTab = "library"
                } label: {
                    HStack(spacing: 6) {
                        Image("icon-plus")
                            .resizable().scaledToFit().frame(width: 16, height: 16)
                        Text("创建知识库")
                            .font(.system(size: 16, weight: .semibold))
                    }
                    .foregroundColor(Color.zxOnPrimary)
                    .frame(maxWidth: .infinity).frame(height: 44)
                    .background(ZXGradient.brand)
                    .clipShape(RoundedRectangle(cornerRadius: 12))
                }
                Button {
                    selectedTab = "library"
                } label: {
                    HStack(spacing: 6) {
                        Image("icon-search")
                            .resizable().scaledToFit().frame(width: 16, height: 16)
                        Text("探索知识库")
                            .font(.system(size: 16, weight: .semibold))
                    }
                    .foregroundColor(Color.zxF0)
                    .frame(maxWidth: .infinity).frame(height: 44)
                    .background(Color.zxFill004)
                    .overlay(RoundedRectangle(cornerRadius: 12).stroke(Color.zxBorder008, lineWidth: 1))
                    .clipShape(RoundedRectangle(cornerRadius: 12))
                }
            }
        }
        .padding(20)
        .background(Color.zxSurfaceElevated)
        .overlay(RoundedRectangle(cornerRadius: 20).stroke(Color.zxHairline, lineWidth: 0.5))
        .clipShape(RoundedRectangle(cornerRadius: 20))
    }

    // MARK: - Small Cards

    private var todayReviewSmallCard: some View {
        NavigationLink(value: Route.reviewCard) {
            HStack(spacing: 14) {
                ZStack {
                    RoundedRectangle(cornerRadius: ZXRadius.md)
                        .fill(Color.zxPurple.opacity(0.12))
                        .frame(width: 44, height: 44)
                    Image(systemName: "arrow.triangle.2.circlepath")
                        .font(.system(size: 20))
                        .foregroundColor(Color.zxPurple)
                }
                VStack(alignment: .leading, spacing: 2) {
                    Text("今日复习")
                        .font(.system(size: 16, weight: .semibold))
                        .foregroundColor(Color.zxF0)
                    Text("\(vm.todayReviewCount) 张卡片 · 约 \(vm.todayReviewEstimatedMinutes) 分钟")
                        .font(.system(size: 14))
                        .foregroundColor(Color.zxF04)
                }
                Spacer()
                Image("icon-chevron-right")
                    .resizable().scaledToFit().frame(width: 16, height: 16)
                    .foregroundColor(Color.zxF03)
            }
            .padding(16)
            .background(Color.zxSurfaceElevated)
            .overlay(RoundedRectangle(cornerRadius: 16).stroke(Color.zxHairline, lineWidth: 0.5))
            .clipShape(RoundedRectangle(cornerRadius: 16))
        }
        .foregroundColor(.primary)
    }

    private var selfTestSmallCard: some View {
        NavigationLink(value: Route.quizList(knowledgeBaseId: "")) {
            HStack(spacing: 14) {
                ZStack {
                    RoundedRectangle(cornerRadius: ZXRadius.md)
                        .fill(Color.zxOrange.opacity(0.12))
                        .frame(width: 44, height: 44)
                    Image(systemName: "list.clipboard")
                        .font(.system(size: 20))
                        .foregroundColor(Color.zxOrange)
                }
                VStack(alignment: .leading, spacing: 2) {
                    Text("资料自测")
                        .font(.system(size: 16, weight: .semibold))
                        .foregroundColor(Color.zxF0)
                    Text("\(vm.availableQuizCount) 个自测可用")
                        .font(.system(size: 14))
                        .foregroundColor(Color.zxF04)
                }
                Spacer()
                Image("icon-chevron-right")
                    .resizable().scaledToFit().frame(width: 16, height: 16)
                    .foregroundColor(Color.zxF03)
            }
            .padding(16)
            .background(Color.zxSurfaceElevated)
            .overlay(RoundedRectangle(cornerRadius: 16).stroke(Color.zxHairline, lineWidth: 0.5))
            .clipShape(RoundedRectangle(cornerRadius: 16))
        }
        .foregroundColor(.primary)
    }

    // MARK: - Weekly Summary

    private var weeklySummaryCard: some View {
        HStack(spacing: 0) {
            weeklyStat("\(vm.weeklyMinutes)", "本周分钟", Color.zxOrange)
            weeklyStat("\(vm.weeklyCardsReviewed)", "复习卡片", Color.zxPurple)
            weeklyStat("\(vm.weeklyActiveDays)", "活跃天数", Color.zxTeal)
            weeklyStat("\(vm.streakDays)", "连续天数", Color.zxAmber)
        }
        .padding(16)
        .background(Color.zxSurfaceElevated)
        .overlay(RoundedRectangle(cornerRadius: 16).stroke(Color.zxHairline, lineWidth: 0.5))
        .clipShape(RoundedRectangle(cornerRadius: 16))
    }

    private func weeklyStat(_ value: String, _ label: String, _ color: Color) -> some View {
        VStack(spacing: 4) {
            Text(value)
                .font(.system(size: 20, weight: .heavy))
                .foregroundColor(color)
            Text(label)
                .font(.system(size: 10))
                .foregroundColor(Color.zxF04)
        }
        .frame(maxWidth: .infinity)
    }

    // MARK: - View Analysis

    private var viewAnalysisLink: some View {
        NavigationLink(value: Route.activeRecall) {
            HStack(spacing: 6) {
                Text("查看完整分析")
                    .font(.system(size: 14, weight: .medium))
                    .foregroundColor(Color.zxPrimary)
                Image("icon-chevron-right")
                    .resizable().scaledToFit().frame(width: 14, height: 14)
                    .foregroundColor(Color.zxPrimary)
            }
        }
        .padding(.vertical, 8)
    }

    // MARK: - Helpers

    private var isReviewMainAction: Bool {
        if case .todaysReview = vm.mainAction { return true }
        return false
    }

    private var isSelfTestMainAction: Bool {
        if case .selfTest = vm.mainAction { return true }
        return false
    }
}
