"""
Vista previa de impresion: reporte de manillas por tipo de paquete.

Formato vertical para impresora termica POS 80mm.
Columnas compactas: Persona | Inicio | Final | Total
"""
import customtkinter as ctk
from datetime import datetime, timedelta
import api
import wristband_tracker

# Orden y filtro de paquetes que aparecen en el reporte
_REPORT_PKG_IDS = ("vip60", "vip180")

# Nombres de fallback si el servidor no responde
_PKG_NAMES_FALLBACK = {
    "vip60":  "VIP 60 MINUTOS",
    "vip180": "VIP-FULL 180 MINUTOS",
}

# Precios de fallback
_PKG_PRICES_FALLBACK = {
    "vip60":  5.00,
    "vip180": 10.00,
}

# Fuente termica (monoespaciada, simula impresora)
_FONT_MONO = "Courier New"


class PrintPreviewDialog(ctk.CTkToplevel):
    """Vista previa del reporte de manillas, formato POS 80mm vertical."""

    def __init__(self, parent, **kwargs):
        super().__init__(parent, **kwargs)
        self.title("Vista previa — Reporte POS 80mm")
        self.geometry("400x720")
        self.resizable(True, True)
        self.grab_set()
        self.lift()
        self.focus_force()

        self.update_idletasks()
        px = parent.winfo_rootx() + parent.winfo_width()  // 2 - 200
        py = parent.winfo_rooty() + parent.winfo_height() // 2 - 360
        self.geometry(f"+{max(0, px)}+{max(0, py)}")

        self._build()

    # ------------------------------------------------------------------
    # Layout
    # ------------------------------------------------------------------

    def _build(self):
        # Barra superior
        toolbar = ctk.CTkFrame(self, fg_color=("#1a1a2e", "#0f0f1a"),
                               height=50, corner_radius=0)
        toolbar.pack(fill="x")
        toolbar.pack_propagate(False)

        ctk.CTkLabel(
            toolbar, text="Vista Previa — POS 80mm",
            font=ctk.CTkFont(size=14, weight="bold"),
            text_color="#cccccc",
        ).pack(side="left", padx=16, pady=12)

        ctk.CTkLabel(
            toolbar,
            text="Formato termica",
            font=ctk.CTkFont(size=10),
            text_color="#445566",
        ).pack(side="left", padx=4)

        ctk.CTkButton(
            toolbar, text="Cerrar",
            width=80, height=32, corner_radius=6,
            fg_color="#37474f", hover_color="#546e7a",
            font=ctk.CTkFont(size=12),
            command=self.destroy,
        ).pack(side="right", padx=12, pady=9)

        # Fondo gris (bandeja de impresion)
        bg = ctk.CTkFrame(self, fg_color=("#bbbbbb", "#2a2a3a"), corner_radius=0)
        bg.pack(fill="both", expand=True)

        scroll = ctk.CTkScrollableFrame(bg, fg_color="transparent", corner_radius=0)
        scroll.pack(fill="both", expand=True)

        # Papel blanco centrado (simula rollo 80mm)
        self._paper = ctk.CTkFrame(
            scroll,
            fg_color="#ffffff",
            corner_radius=2,
            border_width=1,
            border_color="#aaaaaa",
        )
        self._paper.pack(padx=30, pady=16, anchor="center")

        self._build_document()

    # ------------------------------------------------------------------
    # Contenido del ticket
    # ------------------------------------------------------------------

    def _build_document(self):
        p = self._paper
        now = datetime.now()

        # Obtener info de paquetes del servidor (con fallback)
        try:
            pkgs_list = api.get_packages()
            pkg_info = {pkg["id"]: pkg for pkg in pkgs_list}
        except Exception:
            pkg_info = {}

        # ── Encabezado centrado ───────────────────────────────────────
        ctk.CTkLabel(
            p, text="ICEBERG  Manillas POS",
            font=ctk.CTkFont(family=_FONT_MONO, size=12, weight="bold"),
            text_color="#000000",
        ).pack(pady=(14, 0))

        ctk.CTkLabel(
            p, text="Reporte de Manillas",
            font=ctk.CTkFont(family=_FONT_MONO, size=9),
            text_color="#333333",
        ).pack()

        ctk.CTkLabel(
            p,
            text=now.strftime("%d/%m/%Y   %H:%M"),
            font=ctk.CTkFont(family=_FONT_MONO, size=9),
            text_color="#555555",
        ).pack(pady=(0, 4))

        self._separator(p)

        # ── Secciones por tipo de paquete ─────────────────────────────
        all_entries = wristband_tracker.get_all()

        grand_total = 0.0
        grand_count = 0

        for pkg_id in _REPORT_PKG_IDS:
            info       = pkg_info.get(pkg_id, {})
            pkg_name   = info.get("name", _PKG_NAMES_FALLBACK.get(pkg_id, pkg_id)).upper()
            unit_price = float(info.get("price", _PKG_PRICES_FALLBACK.get(pkg_id, 0.0)))
            entries    = [e for e in all_entries if e.get("package_id") == pkg_id]

            # Titulo de seccion
            ctk.CTkLabel(
                p,
                text=pkg_name,
                font=ctk.CTkFont(family=_FONT_MONO, size=9, weight="bold"),
                text_color="#0d47a1",
            ).pack(anchor="w", padx=8, pady=(8, 1))

            # Cabecera de columnas
            col_hdr = ctk.CTkFrame(p, fg_color="#dde4f0", corner_radius=0)
            col_hdr.pack(fill="x", padx=8)

            for text, w, anc in [
                ("Persona",  104, "w"),
                ("Inicio",    48, "center"),
                ("Final",     48, "center"),
                ("Total",     58, "e"),
            ]:
                ctk.CTkLabel(
                    col_hdr, text=text, width=w,
                    font=ctk.CTkFont(family=_FONT_MONO, size=8, weight="bold"),
                    text_color="#1a2a5a", anchor=anc,
                ).pack(side="left", padx=2, pady=3)

            if not entries:
                ctk.CTkLabel(
                    p, text="  (sin ventas en esta sesion)",
                    font=ctk.CTkFont(family=_FONT_MONO, size=8),
                    text_color="#aaaaaa",
                ).pack(anchor="w", padx=10, pady=4)
            else:
                subtotal = 0.0
                for i, e in enumerate(entries):
                    start: datetime = e.get("start_time")
                    if e.get("returned_at"):
                        end: datetime = e["returned_at"]
                    elif start:
                        grace = e.get("grace_minutes", 5)
                        play  = e.get("real_play_minutes", e.get("play_minutes", 0))
                        red   = e.get("red_minutes", 8)
                        end   = start + timedelta(minutes=grace + play + red)
                    else:
                        end = None

                    start_s = start.strftime("%H:%M") if start else "--:--"
                    end_s   = end.strftime("%H:%M")   if end   else "--:--"
                    name    = e.get("name", "(sin nombre)")
                    total   = unit_price
                    subtotal += total

                    row_bg = "#f4f7fc" if i % 2 == 0 else "#ffffff"
                    row = ctk.CTkFrame(p, fg_color=row_bg, corner_radius=0)
                    row.pack(fill="x", padx=8)

                    for text, w, anc in [
                        (name,            104, "w"),
                        (start_s,          48, "center"),
                        (end_s,            48, "center"),
                        (f"${total:.2f}",  58, "e"),
                    ]:
                        ctk.CTkLabel(
                            row, text=text, width=w,
                            font=ctk.CTkFont(family=_FONT_MONO, size=8),
                            text_color="#1a1a1a", anchor=anc,
                        ).pack(side="left", padx=2, pady=3)

                # Subtotal de seccion
                sub = ctk.CTkFrame(p, fg_color="#dde4f0", corner_radius=0)
                sub.pack(fill="x", padx=8, pady=(0, 2))
                ctk.CTkLabel(
                    sub,
                    text=f"  {len(entries)} venta(s)",
                    font=ctk.CTkFont(family=_FONT_MONO, size=8, weight="bold"),
                    text_color="#3a4a7a",
                ).pack(side="left", padx=4, pady=3)
                ctk.CTkLabel(
                    sub,
                    text=f"Sub: ${subtotal:.2f}",
                    font=ctk.CTkFont(family=_FONT_MONO, size=9, weight="bold"),
                    text_color="#0d47a1",
                ).pack(side="right", padx=6, pady=3)

                grand_total += subtotal
                grand_count += len(entries)

        # ── Total general ─────────────────────────────────────────────
        self._separator(p)

        total_row = ctk.CTkFrame(p, fg_color="#ccd8f0", corner_radius=0)
        total_row.pack(fill="x", padx=8, pady=(2, 4))
        ctk.CTkLabel(
            total_row,
            text=f"  TOTAL  {grand_count} venta(s)",
            font=ctk.CTkFont(family=_FONT_MONO, size=9, weight="bold"),
            text_color="#0d1a3a",
        ).pack(side="left", padx=4, pady=4)
        ctk.CTkLabel(
            total_row,
            text=f"${grand_total:.2f}",
            font=ctk.CTkFont(family=_FONT_MONO, size=11, weight="bold"),
            text_color="#0d47a1",
        ).pack(side="right", padx=8, pady=4)

        # ── Pie del ticket ────────────────────────────────────────────
        ctk.CTkLabel(
            p,
            text=f"Generado: {now.strftime('%d/%m/%Y  %H:%M:%S')}",
            font=ctk.CTkFont(family=_FONT_MONO, size=7),
            text_color="#aaaaaa",
        ).pack(anchor="w", padx=8, pady=(4, 14))

    # ------------------------------------------------------------------
    # Helper
    # ------------------------------------------------------------------

    def _separator(self, parent):
        ctk.CTkLabel(
            parent,
            text="─" * 42,
            font=ctk.CTkFont(family=_FONT_MONO, size=8),
            text_color="#cccccc",
        ).pack(padx=6, pady=1)
