package app.voltplan.cable.pdf

import android.content.Context
import android.graphics.Color
import android.graphics.pdf.PdfDocument
import app.voltplan.cable.R
import app.voltplan.cable.data.UnitSystem
import app.voltplan.cable.ui.bom.BomUiState
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/** Renders the bill of materials as a PDF and opens the share sheet. */
object SystemBomPdf {
    private val ACCENT = Color.rgb(115, 87, 219)

    suspend fun exportAndShare(context: Context, state: BomUiState, unit: UnitSystem) {
        val file = withContext(Dispatchers.IO) {
            val doc = PdfDocument()
            val w = PdfWriter(doc)
            w.beginPage()
            w.text(context.getString(R.string.bom_pdf_header_title), 26f, bold = true)
            w.text("${state.systemName} • ${unit.wireAreaUnit}", 13f, Color.DKGRAY)
            w.divider()

            if (state.sections.isEmpty()) {
                w.text(context.getString(R.string.bom_pdf_placeholder_empty), 14f, Color.DKGRAY)
            } else {
                state.sections.forEach { section ->
                    w.gap(8f)
                    w.text(context.getString(section.category.titleRes), 18f, ACCENT, bold = true)
                    w.text(context.getString(section.category.subtitleRes), 11f, Color.GRAY)
                    w.gap(4f)
                    section.items.forEach { item ->
                        w.text("• ${item.metricText}", 12f, ACCENT, bold = true)
                        w.text(item.title, 14f, Color.BLACK, bold = item.isPrimary)
                        if (item.detail.isNotBlank()) w.text(item.detail, 11f, Color.DKGRAY)
                        w.gap(6f)
                    }
                    w.divider()
                }
            }
            w.finish()
            PdfShare.writeToCache(context, "System-BOM-${System.currentTimeMillis()}.pdf", doc)
        }
        withContext(Dispatchers.Main) { PdfShare.share(context, file) }
    }
}
