package comun

import (
	"bytes"
	"encoding/base64"
	"errors"
	"fmt"
	"image"
	_ "image/jpeg"
	"image/png"
	"os"
	"strconv"
	"strings"

	"codeberg.org/go-pdf/fpdf"
)

// LimpiarErrorRuta devuelve el error de archivo sin la ruta: un *os.PathError lleva el
// path, que incluye el nombre del paciente y el título del formato. Conserva la operación
// y la causa para poder diagnosticar, pero no el dato sensible. Un error de otro tipo se
// devuelve tal cual.
func LimpiarErrorRuta(err error) error {
	var pe *os.PathError
	if errors.As(err, &pe) {
		return fmt.Errorf("%s: %w", pe.Op, pe.Err)
	}
	return err
}

type ConfigPDF struct {
	Orientacion string
	Unidad      string
	Tamaño      string
	FontDir     string
	MarginLeft  float64
	MarginRight float64
	FooterH     float64
	LineH       float64
	FontName    string
	FontSize    float64
	CellPadding float64
}

// ConfigCarta es el formato de página de todos los PDFs exportados.
func ConfigCarta() ConfigPDF {
	return ConfigPDF{
		Orientacion: "P",
		Unidad:      "mm",
		Tamaño:      "Letter",
		FontDir:     "",
		MarginLeft:  15,
		MarginRight: 15,
		FooterH:     20,
		LineH:       5,
		FontName:    "LiberationSerif",
		FontSize:    10,
		CellPadding: 1,
	}
}

type Empresa struct {
	Nombre    string
	Subtitulo string
	Footer    string
}

type Reporte struct {
	PDF    *fpdf.Fpdf
	Cfg    ConfigPDF
	Comp   Empresa
	PageW  float64
	PageH  float64
	Usable float64
}

func SanitizarDir(s string) string {
	s = strings.ReplaceAll(s, "/", "-")
	s = strings.ReplaceAll(s, ":", "-")
	return strings.TrimSpace(s)
}

func NuevoReporte(cfg ConfigPDF, comp Empresa) Reporte {
	pdf := fpdf.New(cfg.Orientacion, cfg.Unidad, cfg.Tamaño, cfg.FontDir)

	pdf.AddUTF8Font("LiberationSerif", "", "assets/LiberationSerif-Regular.ttf")
	pdf.AddUTF8Font("LiberationSerif", "B", "assets/LiberationSerif-Bold.ttf")
	pdf.AddUTF8Font("LiberationSerif", "I", "assets/LiberationSerif-Italic.ttf")
	pdf.AddUTF8Font("LiberationSerif", "BI", "assets/LiberationSerif-BoldItalic.ttf")

	pdf.SetMargins(cfg.MarginLeft, 10, cfg.MarginRight)
	pdf.SetAutoPageBreak(true, cfg.FooterH)
	w, h := pdf.GetPageSize()

	r := Reporte{
		PDF:    pdf,
		Cfg:    cfg,
		Comp:   comp,
		PageW:  w,
		PageH:  h,
		Usable: w - cfg.MarginLeft - cfg.MarginRight,
	}

	pdf.SetHeaderFunc(func() {
		pdf.SetFont(cfg.FontName, "B", 13)
		pdf.CellFormat(0, 8, comp.Nombre, "", 1, "C", false, 0, "")
		if comp.Subtitulo != "" {
			pdf.Ln(3)
			pdf.SetFont(cfg.FontName, "B", 12)
			pdf.CellFormat(0, 7, comp.Subtitulo, "", 1, "C", false, 0, "")
		}
		pdf.Ln(2)
		pdf.SetLineWidth(0.5)
		pdf.SetDrawColor(0, 0, 0)
		y := pdf.GetY()
		pdf.Line(cfg.MarginLeft, y, w-cfg.MarginRight, y)
		pdf.Ln(4)
	})

	pdf.AliasNbPages("")
	pdf.SetFooterFunc(func() {
		pdf.SetY(-15)
		pdf.SetFont(cfg.FontName, "", 9)
		if comp.Footer != "" {
			pdf.CellFormat(0, 5, comp.Footer, "", 1, "C", false, 0, "")
		}
		pdf.CellFormat(0, 5, "Página "+strconv.Itoa(pdf.PageNo())+"/{nb}", "", 0, "C", false, 0, "")
	})

	return r
}

func TituloGeneral(r Reporte, title string) {
	r.PDF.SetFont(r.Cfg.FontName, "B", 13)
	r.PDF.CellFormat(0, 8, title, "", 1, "C", false, 0, "")
	r.PDF.Ln(3)
	r.PDF.SetLineWidth(0.4)
	y := r.PDF.GetY()
	r.PDF.Line(r.Cfg.MarginLeft, y, r.PageW-r.Cfg.MarginRight, y)
	r.PDF.Ln(6)
	r.PDF.SetFont(r.Cfg.FontName, "", r.Cfg.FontSize)
}

// SubtituloSeccion abre una sección dentro de un registro: texto en negrita y una línea gris.
func SubtituloSeccion(r Reporte, texto string) {
	r.PDF.Ln(2)
	r.PDF.SetFont(r.Cfg.FontName, "B", r.Cfg.FontSize)
	r.PDF.CellFormat(0, 5, texto, "", 1, "L", false, 0, "")
	r.PDF.SetDrawColor(180, 180, 180)
	y := r.PDF.GetY()
	r.PDF.Line(r.Cfg.MarginLeft, y, r.PageW-r.Cfg.MarginRight, y)
	r.PDF.Ln(1)
}

func FiltrarColsOcultas(cols []string) []string {
	result := make([]string, 0, len(cols))
	for _, c := range cols {
		if !strings.HasPrefix(c, "_") {
			result = append(result, c)
		}
	}
	return result
}

func RenderizarRegistro(r Reporte, etiqueta string, cols []string, row map[string]string) {
	minEspacio := 7 + 2 + r.Cfg.LineH*4
	if r.PDF.GetY()+minEspacio > r.PageH-r.Cfg.FooterH {
		r.PDF.AddPage()
	}

	r.PDF.SetFont(r.Cfg.FontName, "B", r.Cfg.FontSize+1)
	r.PDF.CellFormat(0, 7, etiqueta, "", 1, "L", false, 0, "")
	r.PDF.SetLineWidth(0.1)
	r.PDF.SetDrawColor(160, 160, 160)
	y := r.PDF.GetY()
	r.PDF.Line(r.Cfg.MarginLeft, y, r.PageW-r.Cfg.MarginRight, y)
	r.PDF.Ln(2)

	for _, col := range FiltrarColsOcultas(cols) {
		val := row[col]
		if val == "" {
			continue
		}
		if strings.ContainsRune(val, '\t') {
			r.PDF.SetFont(r.Cfg.FontName, "B", r.Cfg.FontSize)
			r.PDF.CellFormat(0, 5, col+":", "", 1, "L", false, 0, "")
			renderizarTablaInline(r, val)
		} else if len(val) > 65 || strings.ContainsAny(val, "\n\r") {
			r.PDF.SetFont(r.Cfg.FontName, "B", r.Cfg.FontSize)
			r.PDF.CellFormat(0, 5, col+":", "", 1, "L", false, 0, "")
			r.PDF.SetFont(r.Cfg.FontName, "", r.Cfg.FontSize)
			r.PDF.MultiCell(0, 5, val, "", "L", false)
		} else {
			r.PDF.SetFont(r.Cfg.FontName, "B", r.Cfg.FontSize)
			r.PDF.CellFormat(55, 5, col+":", "", 0, "L", false, 0, "")
			r.PDF.SetFont(r.Cfg.FontName, "", r.Cfg.FontSize)
			r.PDF.MultiCell(0, 5, val, "", "L", false)
		}
	}
	r.PDF.Ln(3)
}

func renderizarTablaInline(r Reporte, val string) {
	var data [][]string
	for _, linea := range strings.Split(val, "\n") {
		if linea == "" {
			continue
		}
		data = append(data, strings.Split(linea, "\t"))
	}
	if len(data) > 1 {
		drawTable(r, data)
	}
}

// CrearTablaPdf agrega una tabla con encabezados al reporte.
func CrearTablaPdf(r Reporte, cols []string, rows []map[string]string) {
	if len(rows) == 0 {
		r.PDF.SetFont(r.Cfg.FontName, "I", r.Cfg.FontSize)
		r.PDF.CellFormat(0, 6, "Sin registros.", "", 1, "L", false, 0, "")
		return
	}

	cols = FiltrarColsOcultas(cols)
	data := make([][]string, 0, len(rows)+1)
	data = append(data, cols)
	for _, row := range rows {
		rowData := make([]string, len(cols))
		for i, col := range cols {
			rowData[i] = row[col]
		}
		data = append(data, rowData)
	}
	drawTable(r, data)
}

// CrearParrafosPdf agrega secciones con campos a partir de registros.
// Cada registro es una sección separada por una línea.
// Valores de más de 50 caracteres o con saltos de línea se muestran debajo del nombre del campo.
func CrearParrafosPdf(r Reporte, etiqueta string, cols []string, rows []map[string]string) {
	if len(rows) == 0 {
		r.PDF.SetFont(r.Cfg.FontName, "I", r.Cfg.FontSize)
		r.PDF.CellFormat(0, 6, "Sin registros.", "", 1, "L", false, 0, "")
		return
	}
	cols = FiltrarColsOcultas(cols)
	for idx, row := range rows {
		titulo := etiqueta
		if len(rows) > 1 {
			titulo = fmt.Sprintf("%s #%d", etiqueta, idx+1)
		}

		r.PDF.SetFont(r.Cfg.FontName, "B", r.Cfg.FontSize+1)
		r.PDF.CellFormat(0, 7, titulo, "", 1, "L", false, 0, "")
		r.PDF.SetLineWidth(0.1)
		r.PDF.SetDrawColor(160, 160, 160)
		y := r.PDF.GetY()
		r.PDF.Line(r.Cfg.MarginLeft, y, r.PageW-r.Cfg.MarginRight, y)
		r.PDF.Ln(2)

		for _, col := range cols {
			val := row[col]
			if val == "" {
				continue
			}
			if len(val) > 50 || strings.ContainsAny(val, "\n\r") {
				r.PDF.SetFont(r.Cfg.FontName, "B", r.Cfg.FontSize)
				r.PDF.CellFormat(0, 5, col+":", "", 1, "L", false, 0, "")
				r.PDF.SetFont(r.Cfg.FontName, "", r.Cfg.FontSize)
				r.PDF.MultiCell(0, 5, val, "", "L", false)
			} else {
				r.PDF.SetFont(r.Cfg.FontName, "B", r.Cfg.FontSize)
				r.PDF.CellFormat(55, 5, col+":", "", 0, "L", false, 0, "")
				r.PDF.SetFont(r.Cfg.FontName, "", r.Cfg.FontSize)
				r.PDF.MultiCell(0, 5, val, "", "L", false)
			}
		}
		r.PDF.Ln(5)
	}
}

// InsertarImagenDataURI coloca en el PDF una imagen data URI base64 (PNG/JPEG) con el ancho
// dado y alto proporcional. La decodifica y recodifica a PNG antes de dársela a fpdf: una
// imagen que fpdf no pueda leer lo deja en error permanente y cuelga el render, así que todo
// fallo se devuelve aquí sin tocar el PDF.
func InsertarImagenDataURI(r Reporte, nombre, dataURI string, ancho float64) error {
	cabecera, contenido, ok := strings.Cut(dataURI, ",")
	if !ok || !strings.HasSuffix(cabecera, ";base64") ||
		!(strings.HasPrefix(cabecera, "data:image/png") || strings.HasPrefix(cabecera, "data:image/jpeg")) {
		return fmt.Errorf("la imagen %s no es un data URI PNG/JPEG en base64", nombre)
	}
	crudo, err := base64.StdEncoding.DecodeString(contenido)
	if err != nil {
		return fmt.Errorf("la imagen %s no es base64 válido: %w", nombre, err)
	}
	// La imagen llega de datos del paciente sin validar y image.Decode reserva
	// ancho×alto×4 bytes según la cabecera; sin este tope una firma que declare
	// dimensiones enormes agota la RAM y tumba la exportación. DecodeConfig solo
	// lee la cabecera, así que el rechazo es barato.
	const maxLado = 4000
	cfg, _, err := image.DecodeConfig(bytes.NewReader(crudo))
	if err != nil {
		return fmt.Errorf("la imagen %s no se pudo leer: %w", nombre, err)
	}
	if cfg.Width > maxLado || cfg.Height > maxLado {
		return fmt.Errorf("la imagen %s excede el tamaño permitido: %dx%d", nombre, cfg.Width, cfg.Height)
	}
	img, _, err := image.Decode(bytes.NewReader(crudo))
	if err != nil {
		return fmt.Errorf("la imagen %s no se pudo decodificar: %w", nombre, err)
	}
	var normalizada bytes.Buffer
	if err := png.Encode(&normalizada, img); err != nil {
		return fmt.Errorf("la imagen %s no se pudo recodificar: %w", nombre, err)
	}

	limites := img.Bounds()
	if limites.Dx() == 0 || limites.Dy() == 0 {
		return fmt.Errorf("la imagen %s está vacía", nombre)
	}
	alto := ancho * float64(limites.Dy()) / float64(limites.Dx())
	if r.PDF.GetY()+alto > r.PageH-r.Cfg.FooterH {
		r.PDF.AddPage()
	}

	opciones := fpdf.ImageOptions{ImageType: "PNG"}
	r.PDF.RegisterImageOptionsReader(nombre, opciones, &normalizada)
	r.PDF.ImageOptions(nombre, r.Cfg.MarginLeft, r.PDF.GetY(), ancho, alto, true, opciones, 0, "")
	return nil
}

// GuardarPDF escribe el reporte en ruta. ref es un identificador no sensible (p. ej.
// el código del paciente) para los mensajes de log: ni ref ni la ruta deben llevar el
// nombre del paciente o el título del formato, que son datos de salud fuera del ZIP cifrado.
func GuardarPDF(r Reporte, ruta, ref string) {
	if err := r.PDF.OutputFileAndClose(ruta); err != nil {
		LogFatal(fmt.Errorf("al guardar el PDF de %s: %w", ref, LimpiarErrorRuta(err)))
	}
	LogInfo("PDF generado")
}

// --- Internos para dibujar tabla ---

func drawTable(r Reporte, data [][]string) {
	if len(data) == 0 {
		return
	}
	colW := r.Usable / float64(len(data[0]))
	r.PDF.Ln(2)
	minEspacio := r.Cfg.LineH * 3
	if r.PDF.GetY()+minEspacio > r.PageH-r.Cfg.FooterH {
		r.PDF.AddPage()
	}
	drawHeaderRow(r, data[0], colW)
	for _, row := range data[1:] {
		drawDataRow(r, row, colW, data[0])
	}
	r.PDF.Ln(2)
}

func drawHeaderRow(r Reporte, headers []string, colW float64) {
	r.PDF.SetFont(r.Cfg.FontName, "B", r.Cfg.FontSize)
	r.PDF.SetLineWidth(0.1)
	r.PDF.SetDrawColor(160, 160, 160)
	split := splitCells(r.PDF, headers, colW, r.Cfg.CellPadding)
	rowH := maxHeight(split, r.Cfg.LineH)
	xStart, yStart := r.Cfg.MarginLeft, r.PDF.GetY()

	for col, lines := range split {
		x := xStart + float64(col)*colW
		r.PDF.Rect(x, yStart, colW, rowH, "D")
		offsetY := (rowH - float64(len(lines))*r.Cfg.LineH) / 2
		for i, line := range lines {
			r.PDF.SetXY(x+r.Cfg.CellPadding, yStart+offsetY+float64(i)*r.Cfg.LineH)
			r.PDF.CellFormat(colW-r.Cfg.CellPadding*2, r.Cfg.LineH, line, "", 0, "L", false, 0, "")
		}
	}
	r.PDF.SetXY(xStart, yStart+rowH)
	r.PDF.SetFont(r.Cfg.FontName, "", r.Cfg.FontSize)
}

func drawDataRow(r Reporte, row []string, colW float64, headers []string) {
	r.PDF.SetLineWidth(0.1)
	r.PDF.SetDrawColor(160, 160, 160)
	limit := r.PageH - r.Cfg.FooterH

	split := splitCells(r.PDF, row, colW, r.Cfg.CellPadding)
	maxLines := maxLinesCount(split)
	currentLine := 0

	for currentLine < maxLines {
		// Si fpdf entró en estado de error, sus operaciones de dibujo (incluida
		// AddPage) se vuelven no-op y este bucle no avanzaría nunca. Salir.
		if r.PDF.Err() {
			return
		}
		xStart, yStart := r.Cfg.MarginLeft, r.PDF.GetY()
		linesFit := int((limit - yStart) / r.Cfg.LineH)
		if linesFit <= 0 {
			r.PDF.AddPage()
			drawHeaderRow(r, headers, colW)
			// Guard: si AddPage no avanzó (Y no se redujo) no hay salto de página
			// real; continuar provocaría un bucle infinito.
			if r.PDF.GetY() >= yStart {
				return
			}
			continue
		}
		endLine := min(currentLine+linesFit, maxLines)
		blockH := float64(endLine-currentLine) * r.Cfg.LineH

		for col, cellLines := range split {
			x := xStart + float64(col)*colW
			r.PDF.Rect(x, yStart, colW, blockH, "D")
			for i := currentLine; i < endLine && i < len(cellLines); i++ {
				r.PDF.SetXY(x+r.Cfg.CellPadding, yStart+float64(i-currentLine)*r.Cfg.LineH)
				r.PDF.CellFormat(colW-r.Cfg.CellPadding*2, r.Cfg.LineH, cellLines[i], "", 0, "L", false, 0, "")
			}
		}
		r.PDF.SetXY(xStart, yStart+blockH)
		currentLine = endLine
	}
}

func splitCells(pdf *fpdf.Fpdf, row []string, colW, pad float64) [][]string {
	result := make([][]string, len(row))
	usableW := colW - pad*2
	if usableW <= 0 {
		usableW = 1
	}
	for i, cell := range row {
		if cell == "" {
			result[i] = []string{""}
			continue
		}
		lines := pdf.SplitText(cell, usableW)
		if len(lines) == 0 {
			lines = []string{""}
		}
		result[i] = lines
	}
	return result
}

func maxHeight(split [][]string, lineH float64) float64 {
	m := 1
	for _, lines := range split {
		if len(lines) > m {
			m = len(lines)
		}
	}
	return float64(m) * lineH
}

func maxLinesCount(split [][]string) int {
	m := 0
	for _, lines := range split {
		if len(lines) > m {
			m = len(lines)
		}
	}
	return m
}
