import SwiftUI
import Combine

// MARK: - ViewModel

@MainActor
final class MaterialDetailViewModel: ObservableObject {
    @Published var kb: KnowledgeBase?
    @Published var itemCount: Int = 0
    @Published var quizCount: Int = 0
    @Published var isLoading = true
    @Published var aiStatus: AIStatus = .processing

    enum AIStatus: Equatable {
        case processing  // AI 整理知识点中
        case ready       // 知识点已生成，可开始学习
        case failed(String)
    }

    let knowledgeBaseId: String

    init(knowledgeBaseId: String) {
        self.knowledgeBaseId = knowledgeBaseId
    }

    func load() async {
        isLoading = true
        do {
            kb = try await KnowledgeBaseService.shared.detail(id: knowledgeBaseId)
        } catch {}

        do {
            let items = try await KnowledgeItemService.shared.list(knowledgeBaseId: knowledgeBaseId)
            itemCount = items.count
        } catch {}

        do {
            let quizzes = try await QuizService.shared.list(knowledgeBaseId: knowledgeBaseId)
            quizCount = quizzes.count
        } catch {}

        aiStatus = itemCount > 0 ? .ready : .processing
        isLoading = false
    }
}

// MARK: - Main View

struct MaterialDetailView: View {
    @StateObject private var vm: MaterialDetailViewModel

    let knowledgeBaseId: String
    let fileName: String
    let fileType: MaterialType
    let fileSize: UInt64
    let filePath: String
    let uploadDate: String?

    init(knowledgeBaseId: String, fileName: String, fileType: MaterialType,
         fileSize: UInt64, filePath: String, uploadDate: String? = nil) {
        self.knowledgeBaseId = knowledgeBaseId
        self.fileName = fileName
        self.fileType = fileType
        self.fileSize = fileSize
        self.filePath = filePath
        self.uploadDate = uploadDate
        _vm = StateObject(wrappedValue: MaterialDetailViewModel(knowledgeBaseId: knowledgeBaseId))
    }

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

            ScrollView {
                VStack(spacing: 20) {
                    // MARK: - 原文件区域
                    fileSection

                    // MARK: - 学习内容区域
                    learningSection

                    Spacer().frame(height: 100)
                }
                .padding(.horizontal, 20).padding(.top, 8)
            }
            .scrollIndicators(.hidden)
        }
        .navigationTitle("资料详情")
        .navigationBarTitleDisplayMode(.inline)
        .toolbar(.hidden, for: .tabBar)
        .toolbarBackground(.hidden, for: .navigationBar)
        .task { await vm.load() }
    }

    // MARK: - File section

    var fileSection: some View {
        VStack(alignment: .leading, spacing: 12) {
            HStack(spacing: 4) {
                Image(systemName: "doc.fill").font(.system(size: 11)).foregroundColor(Color.zxF04)
                Text("原文件").font(.system(size: 12, weight: .semibold)).foregroundColor(Color.zxF04)
                    .textCase(.uppercase).tracking(0.5)
            }

            // Status banner
            statusBanner

            // File metadata card
            VStack(spacing: 0) {
                fileInfoRow(icon: "doc", label: "文件名", value: fileName)
                Divider().background(Color.zxBorder008).padding(.leading, 48)
                fileInfoRow(icon: "info.circle", label: "格式", value: fileType.displayName)
                Divider().background(Color.zxBorder008).padding(.leading, 48)
                fileInfoRow(icon: "arrow.down.to.line", label: "大小", value: formatFileSize(fileSize))
                Divider().background(Color.zxBorder008).padding(.leading, 48)
                if let date = uploadDate {
                    fileInfoRow(icon: "calendar", label: "上传时间", value: date)
                }
            }
            .padding(16)
            .background(Color.zxSurfaceElevated)
            .clipShape(RoundedRectangle(cornerRadius: 16))
            .overlay(RoundedRectangle(cornerRadius: 16).stroke(Color.zxHairline, lineWidth: 1))

            // Read original file button
            NavigationLink(value: Route.materialReader(
                materialId: knowledgeBaseId,
                filePath: filePath,
                materialType: fileType
            )) {
                HStack(spacing: 8) {
                    Image(systemName: fileType == .pdf || fileType == .word || fileType == .excel ? "eye" : "book")
                    Text("阅读原文件")
                }
                .font(.system(size: 15, weight: .bold))
                .foregroundColor(.white)
                .frame(maxWidth: .infinity).frame(height: 48)
                .background(ZXGradient.brand)
                .clipShape(RoundedRectangle(cornerRadius: ZXRadius.lg))
            }
        }
    }

    // MARK: - Status banner

    @ViewBuilder
    var statusBanner: some View {
        switch vm.aiStatus {
        case .processing:
            HStack(spacing: 10) {
                ProgressView().tint(Color.zxAmber)
                VStack(alignment: .leading, spacing: 2) {
                    Text("知习正在整理知识点").font(.system(size: 13, weight: .semibold)).foregroundColor(Color.zxAmberDeep)
                    Text("完成后可开始学习和自测").font(.system(size: 12)).foregroundColor(Color.zxAmber)
                }
                Spacer()
            }
            .padding(12)
            .background(Color.zxAmberSoft.opacity(0.3))
            .clipShape(RoundedRectangle(cornerRadius: 10))

        case .ready:
            HStack(spacing: 10) {
                Image(systemName: "checkmark.circle.fill").font(.system(size: 16)).foregroundColor(Color.zxGreen)
                VStack(alignment: .leading, spacing: 2) {
                    Text("资料已上传，可以先阅读原文件").font(.system(size: 13, weight: .semibold)).foregroundColor(Color.zxGreen)
                    Text("知识点已整理完成").font(.system(size: 12)).foregroundColor(Color.zxF04)
                }
                Spacer()
            }
            .padding(12)
            .background(Color.zxMintSoft.opacity(0.3))
            .clipShape(RoundedRectangle(cornerRadius: 10))

        case .failed(let msg):
            HStack(spacing: 10) {
                Image(systemName: "exclamationmark.triangle.fill").font(.system(size: 16)).foregroundColor(Color.zxCoral)
                Text(msg).font(.system(size: 13)).foregroundColor(Color.zxCoral)
                Spacer()
            }
            .padding(12)
            .background(Color.zxCoralSoft.opacity(0.25))
            .clipShape(RoundedRectangle(cornerRadius: 10))
        }
    }

    // MARK: - File info row

    func fileInfoRow(icon: String, label: String, value: String) -> some View {
        HStack(spacing: 12) {
            Image(systemName: icon)
                .font(.system(size: 14)).foregroundColor(Color.zxF03)
                .frame(width: 24, height: 24)
            Text(label).font(.system(size: 13)).foregroundColor(Color.zxF04)
                .frame(width: 60, alignment: .leading)
            Text(value).font(.system(size: 14, weight: .medium)).foregroundColor(Color.zxF0)
                .lineLimit(1)
            Spacer()
        }
        .padding(.vertical, 8)
    }

    // MARK: - Learning section

    var learningSection: some View {
        VStack(alignment: .leading, spacing: 12) {
            HStack(spacing: 4) {
                Image(systemName: "brain.head.profile").font(.system(size: 11)).foregroundColor(Color.zxF04)
                Text("学习内容").font(.system(size: 12, weight: .semibold)).foregroundColor(Color.zxF04)
                    .textCase(.uppercase).tracking(0.5)
            }

            if vm.isLoading {
                HStack { ProgressView().tint(Color.zxPrimary); Text("加载中…").font(.system(size: 14)).foregroundColor(Color.zxF04) }
                    .frame(maxWidth: .infinity).padding(.vertical, 24)
            } else {
                // Stats row
                HStack(spacing: 12) {
                    statBox(count: vm.itemCount, label: "知识点", icon: "lightbulb", color: Color.zxPurple)
                    statBox(count: vm.quizCount, label: "测验", icon: "list.bullet.clipboard", color: Color.zxAccent)
                }

                // Action buttons
                HStack(spacing: 12) {
                    NavigationLink(value: Route.aiChat(context: ChatEntryContext(scopeType: .material, scopeId: nil, scopeName: fileName, parentKnowledgeBaseId: knowledgeBaseId, createdFrom: "material_detail"))) {
                        Label("问这份资料", systemImage: "bubble.left.and.bubble.right")
                            .font(.system(size: 14, weight: .semibold)).foregroundColor(Color.zxF0)
                            .frame(maxWidth: .infinity).frame(height: 44)
                            .background(Color.zxFill005)
                            .clipShape(RoundedRectangle(cornerRadius: 14))
                            .overlay(RoundedRectangle(cornerRadius: 14).stroke(Color.zxBorder008, lineWidth: 1))
                    }

                    NavigationLink(value: Route.learningSession(
                        taskTitle: vm.kb?.title ?? "学习资料",
                        taskType: "study",
                        taskColorHex: "#3D7FFB"
                    )) {
                        Text("开始学习")
                            .font(.system(size: 14, weight: .bold)).foregroundColor(.white)
                            .frame(maxWidth: .infinity).frame(height: 44)
                            .background(ZXGradient.brandPurple)
                            .clipShape(RoundedRectangle(cornerRadius: 14))
                    }
                }

                if vm.aiStatus == .processing {
                    Text("知习正在整理知识点，完成后可开始学习和自测")
                        .font(.system(size: 12)).foregroundColor(Color.zxF03)
                        .frame(maxWidth: .infinity, alignment: .center).padding(.top, 4)
                }
            }
        }
    }

    // MARK: - Stat box

    func statBox(count: Int, label: String, icon: String, color: Color) -> some View {
        VStack(spacing: 6) {
            Image(systemName: icon).font(.system(size: 18)).foregroundColor(color)
            Text("\(count)").font(.system(size: 22, weight: .heavy)).foregroundColor(Color.zxF0)
            Text(label).font(.system(size: 12)).foregroundColor(Color.zxF04)
        }
        .frame(maxWidth: .infinity)
        .padding(.vertical, 16)
        .background(Color.zxSurface).clipShape(RoundedRectangle(cornerRadius: 14))
        .overlay(RoundedRectangle(cornerRadius: 14).stroke(Color.zxBorder008, lineWidth: 1))
    }
}

// MARK: - File size formatter

private func formatFileSize(_ bytes: UInt64) -> String {
    if bytes < 1024 { return "\(bytes) B" }
    if bytes < 1024 * 1024 { return String(format: "%.1f KB", Double(bytes) / 1024) }
    return String(format: "%.1f MB", Double(bytes) / (1024 * 1024))
}
