import SwiftUI
import PDFKit

struct CourseMaterialView: View {
    let weekNumber: Int
    let courseName: String

    private var resourceName: String? {
        // Only Beginner I has bundled PDFs (Beginner_I_W1.pdf … Beginner_I_W8.pdf).
        guard courseName.contains("Beginner I") else { return nil }
        return "Beginner_I_W\(weekNumber)"
    }

    private var pdfURL: URL? {
        guard let name = resourceName else { return nil }
        return Bundle.main.url(forResource: name, withExtension: "pdf")
    }

    var body: some View {
        Group {
            if let url = pdfURL {
                PDFKitView(url: url)
                    .ignoresSafeArea(edges: .bottom)
            } else {
                ContentUnavailableView(
                    "Material unavailable",
                    systemImage: "doc.questionmark",
                    description: Text("No course material is bundled for week \(weekNumber).")
                )
            }
        }
        .navigationTitle("Week \(weekNumber) Material")
        .navigationBarTitleDisplayMode(.inline)
        .toolbar {
            if let url = pdfURL {
                ToolbarItem(placement: .topBarTrailing) {
                    ShareLink(item: url) {
                        Image(systemName: "square.and.arrow.up")
                    }
                }
            }
        }
    }
}

private struct PDFKitView: UIViewRepresentable {
    let url: URL

    func makeUIView(context: Context) -> PDFView {
        let view = PDFView()
        view.document = PDFDocument(url: url)
        view.autoScales = true
        view.displayMode = .singlePageContinuous
        view.displayDirection = .vertical
        view.usePageViewController(false)
        return view
    }

    func updateUIView(_ uiView: PDFView, context: Context) {
        if uiView.document?.documentURL != url {
            uiView.document = PDFDocument(url: url)
        }
    }
}

struct CourseMaterialDestination: Hashable {
    let courseName: String
    let weekNumber: Int
}
