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.calc.ElectricalCalculations
import app.voltplan.cable.calc.SystemMetrics
import app.voltplan.cable.calc.formatDurationHours
import app.voltplan.cable.data.UnitSystem
import app.voltplan.cable.data.model.chemistry
import app.voltplan.cable.data.model.effectivePowerWatts
import app.voltplan.cable.data.model.energyWattHours
import app.voltplan.cable.data.model.usableCapacityAmpHours
import app.voltplan.cable.ui.system.DetailState
import app.voltplan.cable.util.Fmt
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.util.Locale

private val ACCENT = Color.rgb(115, 87, 219)

/** Renders a full system overview PDF and opens the Android share sheet. */
object SystemOverviewPdf {
    suspend fun exportAndShare(context: Context, state: DetailState, unit: UnitSystem) {
        val file = withContext(Dispatchers.IO) {
            val doc = PdfDocument()
            val w = PdfWriter(doc)
            val m = state.metrics
            val name = state.system?.name ?: "System"

            w.beginPage()
            w.text(name, 26f, bold = true)
            w.text("${context.getString(R.string.overview_pdf_summary_title)} • ${unit.wireAreaUnit}", 13f, Color.DKGRAY)
            w.divider()

            // Summary metrics
            summaryLine(w, context.getString(R.string.overview_pdf_summary_runtime), m.estimatedRuntimeHours?.let { formatDurationHours(it) } ?: "—")
            summaryLine(w, context.getString(R.string.overview_pdf_summary_chargetime), m.estimatedChargeHours?.let { formatDurationHours(it) } ?: "—")
            summaryLine(w, context.getString(R.string.overview_pdf_summary_totalpower), "${Fmt.number(m.totalPower)} W")
            summaryLine(w, context.getString(R.string.overview_pdf_summary_totalcurrent), "${Fmt.number(m.totalCurrent)} A")
            summaryLine(w, context.getString(R.string.overview_pdf_summary_batterycapacity), "${Fmt.number(m.totalCapacity)} Ah")
            summaryLine(w, context.getString(R.string.overview_pdf_summary_chargerpower), "${Fmt.number(m.totalChargerPower)} W")

            if (state.loads.isNotEmpty()) {
                w.gap(12f); w.text(context.getString(R.string.overview_pdf_loads_section), 18f, ACCENT, bold = true); w.divider()
                state.loads.forEach { load ->
                    w.text(load.name, 14f, bold = true)
                    val cs = ElectricalCalculations.recommendedCrossSection(load.length, load.current, load.voltage, unit)
                    val gauge = if (unit == UnitSystem.METRIC) String.format(Locale.US, "%.1f mm²", cs) else "${ElectricalCalculations.formatAWG(cs)} AWG"
                    val vdrop = ElectricalCalculations.voltageDropPercentage(load.length, load.current, load.voltage, unit)
                    summaryLine(w, "${context.getString(R.string.overview_pdf_load_voltage)} / ${context.getString(R.string.overview_pdf_load_current)}", String.format(Locale.US, "%.1f V / %.1f A", load.voltage, load.current))
                    summaryLine(w, "${context.getString(R.string.overview_pdf_load_power)} / ${context.getString(R.string.overview_pdf_load_cable)}", "${Fmt.number(load.power)} W / $gauge")
                    summaryLine(w, "${context.getString(R.string.overview_pdf_load_vdrop)} / ${context.getString(R.string.overview_pdf_load_fuse)}", String.format(Locale.US, "%.1f%% / %.0f A", vdrop, ElectricalCalculations.recommendedFuse(load.current)))
                    w.divider()
                }
            }

            if (state.batteries.isNotEmpty()) {
                w.gap(12f); w.text(context.getString(R.string.overview_pdf_batteries_section), 18f, ACCENT, bold = true); w.divider()
                state.batteries.forEach { b ->
                    w.text(b.name, 14f, bold = true)
                    summaryLine(w, "${context.getString(R.string.overview_pdf_battery_chemistry)} / ${context.getString(R.string.overview_pdf_battery_voltage)}", "${b.chemistry.displayName} / ${Fmt.number(b.nominalVoltage)} V")
                    summaryLine(w, "${context.getString(R.string.overview_pdf_battery_capacity)} / ${context.getString(R.string.overview_pdf_battery_usable)}", "${Fmt.number(b.capacityAmpHours)} Ah / ${Fmt.number(b.usableCapacityAmpHours)} Ah")
                    summaryLine(w, context.getString(R.string.overview_pdf_battery_energy), "${Fmt.number(b.energyWattHours)} Wh")
                    w.divider()
                }
            }

            if (state.chargers.isNotEmpty()) {
                w.gap(12f); w.text(context.getString(R.string.overview_pdf_chargers_section), 18f, ACCENT, bold = true); w.divider()
                state.chargers.forEach { c ->
                    w.text(c.name, 14f, bold = true)
                    summaryLine(w, "${context.getString(R.string.overview_pdf_charger_input)} / ${context.getString(R.string.overview_pdf_charger_output)}", "${Fmt.number(c.inputVoltage)} V / ${Fmt.number(c.outputVoltage)} V")
                    summaryLine(w, "${context.getString(R.string.overview_pdf_charger_current)} / ${context.getString(R.string.overview_pdf_charger_power)}", "${Fmt.number(c.maxCurrentAmps)} A / ${Fmt.number(c.effectivePowerWatts)} W")
                    w.divider()
                }
            }

            w.finish()
            PdfShare.writeToCache(context, "System-Overview-${System.currentTimeMillis()}.pdf", doc)
        }
        withContext(Dispatchers.Main) {
            app.voltplan.cable.analytics.Analytics.log("Overview PDF Shared", mapOf("system" to (state.system?.name ?: "")))
            PdfShare.share(context, file)
        }
    }

    private fun summaryLine(w: PdfWriter, label: String, value: String) {
        w.text("$label:  $value", 12f, Color.DKGRAY)
    }
}
