"""
sidebar.py — Odoo-style vertical navigation sidebar with Toggle support
"""
import os as _os
from PySide6.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, QFrame, QSizePolicy
)
from PySide6.QtCore import Qt, Signal, QPropertyAnimation, QEasingCurve, QSize
from PySide6.QtGui import QFont, QIcon

# Icon asset directory
_ASSETS = _os.path.join(_os.path.dirname(__file__), "assets")

NAV_ITEMS = [
    {"id": "dashboard",  "icon_file": "icon_dashboard.png",  "label": "Tổng Quan"},
    {"id": "customers",  "icon_file": "icon_customers.png",  "label": "Khách Hàng"},
    {"id": "hkd_tax",    "icon_file": "icon_hkd_tax.png",    "label": "Hợp Đồng"},
    {"id": "pdf_tools",  "icon_file": "action_pdf_128.png",  "label": "Công Cụ PDF"},
    {"id": "revenue",    "icon_file": "icon_revenue.png",    "label": "Số Thu / Chi"},
    {"id": "s1a_book",   "icon_file": "icon_s1a_book.png",   "label": "Sổ Doanh Thu"},
    {"id": "support", "icon_file": "action_mail_128.png", "label": "Hỗ trợ"},
    {"id": "guide", "icon_file": "action_view_128.png", "label": "Hướng dẫn"},
    {"id": "packages", "icon_file": "action_report1_128.png", "label": "Gói số"},
    {"id": "feedback", "icon_file": "icon_feedback_pen_chat.svg", "label": "Phản hồi"},
    # {"id": "inventory", "icon_file": "icon_inventory.png", "label": "Kho Hàng"}, # Ẩn cho Nhóm 1
    # {"id": "journal", "icon_file": "icon_journal.png", "label": "Nhật Ký / Chứng Từ"}, # Ẩn cho Nhóm 1
    {"id": "settings",   "icon_file": "icon_settings.png",   "label": "Cài Đặt"},
]

SIDEBAR_EXPANDED_W = 220
SIDEBAR_COLLAPSED_W = 58


def _load_icon(filename: str) -> QIcon:
    path = _os.path.join(_ASSETS, filename)
    if _os.path.exists(path):
        return QIcon(path)
    return QIcon()


class Sidebar(QWidget):
    """Sidebar navigation widget — Odoo style with collapse/expand toggle."""

    page_changed = Signal(str)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setObjectName("sidebar")
        self._active_id = "dashboard"
        self._buttons: dict[str, QPushButton] = {}
        self._expanded = True
        self.setFixedWidth(SIDEBAR_EXPANDED_W)

        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)

        # ── Logo area ─────────────────────────────────────────────────
        logo_frame = QFrame()
        logo_frame.setObjectName("sidebar_logo")
        logo_frame.setFixedHeight(95)  # Tăng chiều cao khu vực logo
        # Khớp tự động theo màu sidebar (xóa background-color bị fix cứng)
        logo_hbox = QHBoxLayout(logo_frame)
        logo_hbox.setContentsMargins(4, 4, 4, 4)
        logo_hbox.setSpacing(0)

        # App icon + text block
        logofull_path = _os.path.join(_ASSETS, "logofull.png")
        app_icon_path = _os.path.join(_ASSETS, "app_icon.png")
        
        if _os.path.exists(logofull_path):
            # Hiển thị logofull.png to hết khu vực logo sidebar
            from PySide6.QtGui import QPixmap
            logo_img_lbl = QLabel()
            logo_img_lbl.setAlignment(Qt.AlignmentFlag.AlignCenter)
            # Dùng transparent để trong suốt hoàn toàn giống nền sidebar
            logo_img_lbl.setStyleSheet("background: transparent; border: none;")
            pix = QPixmap(logofull_path)
            # Scale vừa khu vực: rộng 212px, cao 87px
            logo_img_lbl.setPixmap(pix.scaled(212, 87, Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation))
            self._logo_img_lbl = logo_img_lbl
            logo_hbox.addWidget(logo_img_lbl, stretch=1)
        else:
            # Fallback: icon + text
            app_icon_lbl = QLabel()
            if _os.path.exists(app_icon_path):
                app_icon_lbl.setPixmap(QIcon(app_icon_path).pixmap(QSize(36, 36)))
            app_icon_lbl.setFixedSize(36, 36)
            logo_hbox.addWidget(app_icon_lbl)
            logo_text_block = QWidget()
            logo_text_block.setStyleSheet("background: transparent;")
            logo_text_layout = QVBoxLayout(logo_text_block)
            logo_text_layout.setContentsMargins(0, 0, 0, 0)
            logo_text_layout.setSpacing(1)
            self._logo_text = QLabel("INI HD")
            self._logo_text.setObjectName("sidebar_logo_text")
            self._logo_text.setFont(QFont("Segoe UI", 12, QFont.Weight.Bold))
            self._sub_text = QLabel("Hợp Đồng & Doanh Thu")
            self._sub_text.setObjectName("sidebar_sub_text")
            self._sub_text.setFont(QFont("Segoe UI", 8))
            logo_text_layout.addWidget(self._logo_text)
            logo_text_layout.addWidget(self._sub_text)
            logo_hbox.addWidget(logo_text_block, stretch=1)
            self._app_icon_lbl = app_icon_lbl

        layout.addWidget(logo_frame)

        # ── Nav items ─────────────────────────────────────
        self._nav_container = QWidget()
        nav_layout = QVBoxLayout(self._nav_container)
        nav_layout.setContentsMargins(0, 8, 0, 8)
        nav_layout.setSpacing(2)

        for item in NAV_ITEMS:
            btn = QPushButton(f"  {item['label']}")
            btn.setObjectName("nav_btn")
            btn.setCursor(Qt.CursorShape.PointingHandCursor)
            btn.setFixedHeight(44)
            btn.setProperty("page_id", item["id"])
            btn.setProperty("label_text", item["label"])

            # Set icon
            icon = _load_icon(item["icon_file"])
            if not icon.isNull():
                btn.setIcon(icon)
                btn.setIconSize(QSize(22, 22))

            btn.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
            btn.clicked.connect(self._on_nav_click)
            self._buttons[item["id"]] = btn
            nav_layout.addWidget(btn)

        layout.addWidget(self._nav_container)
        layout.addStretch()

        # ── Footer ────────────────────────────────────────
        self._footer = QLabel("© 2026 INI Software VN")
        self._footer.setObjectName("label_muted")
        self._footer.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self._footer.setContentsMargins(10, 6, 10, 12)
        self._footer.setFont(QFont("Segoe UI", 8))
        layout.addWidget(self._footer)

        self._set_active("dashboard")

    # ── Toggle ────────────────────────────────────────────

    def toggle_sidebar(self):
        """Thu gọn hoặc mở rộng sidebar với animation."""
        self._expanded = not self._expanded
        target_w = SIDEBAR_EXPANDED_W if self._expanded else SIDEBAR_COLLAPSED_W

        self._anim_min = QPropertyAnimation(self, b"minimumWidth")
        self._anim_min.setDuration(220)
        self._anim_min.setEasingCurve(QEasingCurve.Type.InOutCubic)
        self._anim_min.setStartValue(self.width())
        self._anim_min.setEndValue(target_w)

        self._anim_max = QPropertyAnimation(self, b"maximumWidth")
        self._anim_max.setDuration(220)
        self._anim_max.setEasingCurve(QEasingCurve.Type.InOutCubic)
        self._anim_max.setStartValue(self.width())
        self._anim_max.setEndValue(target_w)

        self._anim_min.start()
        self._anim_max.start()

        if self._expanded:
            self._logo_text.show()
            self._sub_text.show()
            self._footer.show()
            for btn in self._buttons.values():
                label = btn.property("label_text")
                btn.setText(f"  {label}")
                btn.setIconSize(QSize(22, 22))
        else:
            self._logo_text.hide()
            self._sub_text.hide()
            self._footer.hide()
            for btn in self._buttons.values():
                btn.setText("")  # Chỉ hiện icon
                btn.setIconSize(QSize(28, 28))

    # ── Nav click ─────────────────────────────────────────

    def _on_nav_click(self):
        btn = self.sender()
        page_id = btn.property("page_id")
        self._set_active(page_id)
        self.page_changed.emit(page_id)

    def _set_active(self, page_id: str):
        if self._active_id in self._buttons:
            old_btn = self._buttons[self._active_id]
            old_btn.setProperty("active", "false")
            old_btn.style().unpolish(old_btn)
            old_btn.style().polish(old_btn)

        self._active_id = page_id
        if page_id in self._buttons:
            new_btn = self._buttons[page_id]
            new_btn.setProperty("active", "true")
            new_btn.style().unpolish(new_btn)
            new_btn.style().polish(new_btn)
