"""
Panel de historial de ventas de la sesion.
Fuente primaria: wristband_tracker (en memoria, siempre disponible).
Fuente secundaria: api.get_daily_report() para el total acumulado del servidor.
Se refresca cada 15 segundos y al completar una venta.
"""
import customtkinter as ctk
from datetime import datetime
import api
import session
import wristband_tracker

REFRESH_INTERVAL_MS = 15_000   # 15 segundos

STATUS_LABELS = {
    "grace":   "Gracia",
    "playing": "Jugando",
    "expired": "Vencida",
    "returned": "Devuelta",
}
STATUS_COLORS = {
    "grace":   "#4caf50",
    "playing": "#2196f3",
    "expired": "#f44336",
    "returned": "#888888",
}

PAYMENT_LABELS = {
    "cash":     "Efectivo",
    "transfer": "Transfer.",
    "card":     "Tarjeta",
}


class HistoryPanel(ctk.CTkFrame):
    """Lista de pulseras vendidas en la sesion actual."""

    def __init__(self, parent, **kwargs):
        super().__init__(parent, fg_color="transparent", **kwargs)
        self._build_ui()
        self.refresh()
        self._schedule_refresh()

    def _build_ui(self):
        # Cabecera de columnas
        header_row = ctk.CTkFrame(self, fg_color=("#111827", "#0a0f1a"), corner_radius=6)
        header_row.pack(fill="x", pady=(0, 4))

        for text, width, anchor in [
            ("Hora",      44,  "center"),
            ("Nombre",   120,  "w"),
            ("Paquete",  130,  "w"),
            ("Pago",      60,  "center"),
            ("Monto",     56,  "e"),
            ("Estado",    62,  "center"),
        ]:
            ctk.CTkLabel(
                header_row, text=text, width=width,
                font=ctk.CTkFont(size=10, weight="bold"),
                text_color="#666666", anchor=anchor,
            ).pack(side="left", padx=3, pady=4)

        # Zona scrolleable
        self._scroll = ctk.CTkScrollableFrame(
            self,
            fg_color=("gray80", "#0d1117"),
            corner_radius=8,
        )
        self._scroll.pack(fill="both", expand=True)

        # Footer: totales
        self._footer = ctk.CTkFrame(self, height=48,
                                    fg_color=("gray75", "#0a0f1a"),
                                    corner_radius=8)
        self._footer.pack(fill="x", pady=(6, 0))
        self._footer.grid_propagate(False)

        self._lbl_total_sales = ctk.CTkLabel(
            self._footer,
            text="0 ventas",
            font=ctk.CTkFont(size=13, weight="bold"),
            text_color="#cccccc",
        )
        self._lbl_total_sales.pack(side="left", padx=14, pady=10)

        self._lbl_total_revenue = ctk.CTkLabel(
            self._footer,
            text="$0.00",
            font=ctk.CTkFont(size=15, weight="bold"),
            text_color="#4caf50",
        )
        self._lbl_total_revenue.pack(side="right", padx=14, pady=10)

    # ------------------------------------------------------------------
    # Refresco
    # ------------------------------------------------------------------

    def refresh(self):
        """Redibuja la lista con los datos del tracker de sesion."""
        entries = wristband_tracker.get_all()

        # Limpiar filas anteriores
        for w in self._scroll.winfo_children():
            w.destroy()

        if not entries:
            ctk.CTkLabel(
                self._scroll,
                text="Sin ventas en esta sesion",
                font=ctk.CTkFont(size=13),
                text_color="#555555",
            ).pack(pady=20)
        else:
            for entry in reversed(entries):
                self._add_row(entry)

        # Totales: preferir datos del servidor; si no, calcular local
        self._update_totals(entries)

    def _add_row(self, entry: dict):
        row = ctk.CTkFrame(
            self._scroll,
            fg_color=("gray85", "#161b22"),
            corner_radius=6,
        )
        row.pack(fill="x", pady=2, padx=2)

        # Hora de entrada
        start: datetime = entry.get("start_time")
        time_str = start.strftime("%H:%M") if start else "--:--"
        ctk.CTkLabel(
            row, text=time_str, width=44,
            font=ctk.CTkFont(size=11), text_color="#888888", anchor="center",
        ).pack(side="left", padx=(8, 2), pady=6)

        # Nombre del cliente
        name = entry.get("name", "(sin nombre)")
        ctk.CTkLabel(
            row, text=name, width=120,
            font=ctk.CTkFont(size=12, weight="bold"),
            text_color="#cccccc", anchor="w",
        ).pack(side="left", padx=2, pady=6)

        # Paquete
        pkg_name = entry.get("package_name", entry.get("package_id", ""))
        ctk.CTkLabel(
            row, text=pkg_name, width=130,
            font=ctk.CTkFont(size=11),
            text_color="#aaaaaa", anchor="w",
        ).pack(side="left", padx=2, pady=6)

        # Metodo de pago (no guardado en tracker, mostrar "-")
        ctk.CTkLabel(
            row, text="-", width=60,
            font=ctk.CTkFont(size=10),
            text_color="#666666", anchor="center",
        ).pack(side="left", padx=2)

        # Monto
        # El tracker no guarda monto directamente, usamos el precio del paquete via session
        # Por ahora mostramos "-"; se puede extender guardando el monto en tracker
        ctk.CTkLabel(
            row, text="-", width=56,
            font=ctk.CTkFont(size=12, weight="bold"),
            text_color="#4caf50", anchor="e",
        ).pack(side="left", padx=4)

        # Estado actual
        status = entry.get("status", "")
        color = STATUS_COLORS.get(status, "#888888")
        label = STATUS_LABELS.get(status, status)
        ctk.CTkLabel(
            row, text=label, width=62,
            font=ctk.CTkFont(size=10),
            text_color=color, anchor="center",
        ).pack(side="right", padx=8)

    def _update_totals(self, local_entries: list):
        """Intenta obtener totales del servidor; si falla usa conteo local."""
        report = api.get_daily_report()
        if isinstance(report, dict) and not report.get("error"):
            total = report.get("total_sales", 0)
            revenue = report.get("total_revenue", 0.0)
            self._lbl_total_sales.configure(
                text=f"{total} venta{'s' if total != 1 else ''}"
            )
            self._lbl_total_revenue.configure(text=f"${revenue:.2f}")
        else:
            # Fallback: conteo local de la sesion
            total = len(local_entries)
            self._lbl_total_sales.configure(
                text=f"{total} venta{'s' if total != 1 else ''} (sesion)"
            )
            self._lbl_total_revenue.configure(text="")

    # ------------------------------------------------------------------
    # Auto-refresco
    # ------------------------------------------------------------------

    def _schedule_refresh(self):
        self.after(REFRESH_INTERVAL_MS, self._auto_refresh)

    def _auto_refresh(self):
        self.refresh()
        self._schedule_refresh()
