"""
dashboard.py — Dashboard / Trang chủ
Giao diện tổng quan đơn giản, thân thiện cho Hộ Kinh Doanh Nhóm 1 & 2.
"""
import os
from datetime import date, datetime
from PySide6.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QLabel, QFrame,
    QScrollArea, QProgressBar, QSizePolicy
)
from PySide6.QtCore import Qt
from PySide6.QtGui import QFont

from gui.theme import COLORS
from core.revenue_db import REVENUE_THRESHOLD


# ─────────────────────────────────────────────────────────────────────────────
# Helpers
# ─────────────────────────────────────────────────────────────────────────────

def _fmt_vnd(amount: float) -> str:
    if amount >= 1_000_000_000:
        return f"{amount / 1_000_000_000:.2f} tỷ đ"
    if amount >= 1_000_000:
        return f"{amount / 1_000_000:.1f}tr đ"
    return f"{amount:,.0f} đ"


# ─────────────────────────────────────────────────────────────────────────────
# Stat Card
# ─────────────────────────────────────────────────────────────────────────────

class StatCard(QFrame):
    """Thẻ KPI đơn – tiêu đề nhỏ + số lớn + ghi chú."""

    def __init__(self, icon: str, title: str, value: str,
                 sub: str = "", accent: str = "", parent=None):
        super().__init__(parent)
        self.setObjectName("stat_card")
        self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
        self.setMinimumHeight(120)

        self._val_lbl = QLabel(value)
        accent = accent or COLORS["text_primary"]

        layout = QVBoxLayout(self)
        layout.setContentsMargins(22, 18, 22, 18)
        layout.setSpacing(6)

        # Icon + tiêu đề
        top = QHBoxLayout()
        icon_lbl = QLabel(icon)
        icon_lbl.setFont(QFont("Segoe UI", 20))
        icon_lbl.setStyleSheet("background: transparent; border: none;")
        title_lbl = QLabel(title)
        title_lbl.setFont(QFont("Segoe UI", 9))
        title_lbl.setStyleSheet(f"color: {COLORS['text_muted']}; background: transparent; border: none;")
        title_lbl.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)
        top.addWidget(icon_lbl)
        top.addWidget(title_lbl, stretch=1)
        layout.addLayout(top)

        # Số tiền chính
        self._val_lbl.setFont(QFont("Segoe UI", 22, QFont.Weight.Bold))
        self._val_lbl.setStyleSheet(f"color: {accent}; background: transparent; border: none;")
        layout.addWidget(self._val_lbl)

        # Subtitle
        if sub:
            sub_lbl = QLabel(sub)
            sub_lbl.setFont(QFont("Segoe UI", 8))
            sub_lbl.setStyleSheet(f"color: {COLORS['text_muted']}; background: transparent; border: none;")
            layout.addWidget(sub_lbl)

    def set_value(self, v: str):
        self._val_lbl.setText(v)

    def set_accent(self, color: str):
        self._val_lbl.setStyleSheet(f"color: {color}; background: transparent; border: none;")


# ─────────────────────────────────────────────────────────────────────────────
# Revenue Progress Bar Widget
# ─────────────────────────────────────────────────────────────────────────────

class RevenueProgressBar(QFrame):
    """Thanh tiến độ doanh thu theo 3 nhóm (QĐ 3389/QĐ-BTC)."""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setObjectName("card")

        layout = QVBoxLayout(self)
        layout.setContentsMargins(24, 20, 24, 20)
        layout.setSpacing(14)

        # — Header row —
        header = QHBoxLayout()
        h_title = QLabel("📊  Doanh thu năm — Theo dõi ngưỡng pháp lý")
        h_title.setFont(QFont("Segoe UI", 12, QFont.Weight.Bold))
        h_title.setStyleSheet("background: transparent;")

        self.val_lbl = QLabel("0 đ")
        self.val_lbl.setFont(QFont("Segoe UI", 14, QFont.Weight.Bold))
        self.val_lbl.setStyleSheet(f"color: {COLORS['accent']}; background: transparent;")

        header.addWidget(h_title)
        header.addStretch()
        header.addWidget(self.val_lbl)
        layout.addLayout(header)

        # — Progress bar —
        self.progress = QProgressBar()
        self.progress.setMinimum(0)
        self.progress.setMaximum(100)   # 0–100 % (tương ứng 0–3 tỷ)
        self.progress.setValue(0)
        self.progress.setTextVisible(False)
        self.progress.setFixedHeight(28)
        self._set_bar_color(COLORS["success"])

        layout.addWidget(self.progress)

        # — Mốc cảnh báo (NQ 198/2025/QH15) —
        milestones = QHBoxLayout()
        for txt, align, color in [
            ("≤ 500tr\nBáo cáo năm 1 lần",        Qt.AlignmentFlag.AlignLeft,   COLORS["success"]),
            ("1 tỷ\nBắt buộc HĐĐT/POS",           Qt.AlignmentFlag.AlignCenter, COLORS["warning"]),
            ("3 tỷ\nVượt mức kê khai",            Qt.AlignmentFlag.AlignRight,  COLORS["danger"]),
        ]:
            lbl = QLabel(txt)
            lbl.setFont(QFont("Segoe UI", 8))
            lbl.setStyleSheet(f"color: {color}; background: transparent;")
            lbl.setAlignment(align)
            milestones.addWidget(lbl)
        layout.addLayout(milestones)

        # — Alert message —
        self.alert_msg = QLabel("✅  An toàn — Doanh thu dưới ngưỡng 500 triệu.")
        self.alert_msg.setFont(QFont("Segoe UI", 10, QFont.Weight.Bold))
        self.alert_msg.setStyleSheet(f"color: {COLORS['success']}; background: transparent;")
        self.alert_msg.setWordWrap(True)
        layout.addWidget(self.alert_msg)

    def _set_bar_color(self, color: str):
        self.progress.setStyleSheet(f"""
            QProgressBar {{
                border: none;
                border-radius: 14px;
                background-color: {COLORS['border']};
            }}
            QProgressBar::chunk {{
                background-color: {color};
                border-radius: 14px;
            }}
        """)

    def update_revenue(self, rev: float):
        from core.revenue_db import HKD_GROUPS, classify_hkd_group
        self.val_lbl.setText(_fmt_vnd(rev))

        # Thanh tiến độ: scale 0–3 tỷ (tối đa Nhóm 2)
        MAX_SCALE = 3_000_000_000
        pct = int(min(100, (rev / MAX_SCALE) * 100)) if rev > 0 else 0
        self.progress.setValue(pct)

        g = classify_hkd_group(rev)
        gn = g["group"]

        if gn == 1:
            color = COLORS["success"]
            msg = f"✅  {g['label']}: {g['note']}"
        elif gn == 2:
            color = COLORS["warning"]
            msg = f"⚖️  {g['label']}: {g['note']}"
        elif gn == 3:
            color = COLORS["danger"]
            msg = f"🚨  {g['label']}: {g['note']}"
        else:
            color = COLORS["danger"]
            msg = f"❌  {g['label']}: {g['note']}"

        self._set_bar_color(color)
        self.alert_msg.setText(msg)
        self.alert_msg.setStyleSheet(f"color: {color}; background: transparent;")


# ─────────────────────────────────────────────────────────────────────────────
# Timeline Card (Deadline Reminder)
# ─────────────────────────────────────────────────────────────────────────────

def _deadline_card(title: str, due: str, status: str, status_color: str) -> QFrame:
    """Tạo một thẻ nhắc nhở deadline dạng card."""
    card = QFrame()
    card.setObjectName("card")
    card_layout = QHBoxLayout(card)
    card_layout.setContentsMargins(18, 14, 18, 14)
    card_layout.setSpacing(16)

    # Left: dot indicator
    dot = QLabel("●")
    dot.setFont(QFont("Segoe UI", 16))
    dot.setStyleSheet(f"color: {status_color}; background: transparent; border: none;")
    dot.setFixedWidth(20)

    # Center: info
    info = QVBoxLayout()
    title_lbl = QLabel(title)
    title_lbl.setFont(QFont("Segoe UI", 10, QFont.Weight.Bold))
    title_lbl.setStyleSheet("background: transparent; border: none;")
    due_lbl = QLabel(f"Hạn: {due}")
    due_lbl.setFont(QFont("Segoe UI", 9))
    due_lbl.setStyleSheet(f"color: {COLORS['text_muted']}; background: transparent; border: none;")
    info.addWidget(title_lbl)
    info.addWidget(due_lbl)

    # Right: badge
    badge = QLabel(status)
    badge.setFont(QFont("Segoe UI", 9, QFont.Weight.Bold))
    badge.setStyleSheet(f"color: {status_color}; background: transparent; border: none;")
    badge.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
    badge.setFixedWidth(100)

    card_layout.addWidget(dot)
    card_layout.addLayout(info, stretch=1)
    card_layout.addWidget(badge)
    return card


# ─────────────────────────────────────────────────────────────────────────────
# Dashboard Page
# ─────────────────────────────────────────────────────────────────────────────

class DashboardPage(QWidget):
    """Trang chủ — Tổng quan Hộ Kinh Doanh (Nhóm 1 & 2)."""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setObjectName("content_area")
        self._build_ui()

    def _build_ui(self):
        root = QVBoxLayout(self)
        root.setContentsMargins(0, 0, 0, 0)
        root.setSpacing(0)



        # ── Scrollable body ──────────────────────────────────
        scroll = QScrollArea()
        scroll.setWidgetResizable(True)
        scroll.setFrameShape(QFrame.Shape.NoFrame)
        scroll.setStyleSheet("background: transparent;")

        body = QWidget()
        body.setStyleSheet("background: transparent;")
        body_layout = QVBoxLayout(body)
        body_layout.setContentsMargins(16, 24, 16, 28)
        body_layout.setSpacing(20)

        # ── 3 KPI Cards ────────────────────────────────────
        kpi_row = QHBoxLayout()
        kpi_row.setSpacing(16)

        self.kpi_thu   = StatCard("🟢", "Tiền Thu hôm nay",     "0 đ",    "Tổng tiền vào trong ngày",        COLORS["success"])
        self.kpi_chi   = StatCard("🔴", "Tiền Chi hôm nay",     "0 đ",    "Tổng tiền ra trong ngày",         COLORS["danger"])
        self.kpi_year  = StatCard("📆", "Doanh thu năm 2026",   "0 đ",    "Tổng thu từ đầu năm đến nay",     COLORS["accent"])
        self.kpi_group = StatCard("🏷️", "Hình thức kê khai",   "Tự kê khai", "Theo Luật 108/2025/QH15",        COLORS["text_primary"])

        for card in [self.kpi_thu, self.kpi_chi, self.kpi_year, self.kpi_group]:
            kpi_row.addWidget(card)

        body_layout.addLayout(kpi_row)

        # ── Revenue Progress Bar ─────────────────────────────
        self.revenue_bar = RevenueProgressBar()
        body_layout.addWidget(self.revenue_bar)

        # ── Legal Rules Summary ──────────────────────────────
        rules_frame = QFrame()
        rules_frame.setObjectName("card")
        rules_layout = QVBoxLayout(rules_frame)
        rules_layout.setContentsMargins(22, 18, 22, 18)
        rules_layout.setSpacing(10)

        rules_title = QLabel("⚖️  Cập nhật Luật thuế 2026 (Số 108/2025 & 109/2025)")
        rules_title.setFont(QFont("Segoe UI", 11, QFont.Weight.Bold))
        rules_title.setStyleSheet(f"color: {COLORS['accent']}; background: transparent;")
        rules_layout.addWidget(rules_title)

        rules_data = [
            (COLORS["success"], "Miễn thuế  ≤ 500tr",  "Miễn hoàn toàn GTGT & TNCN. Không cần nộp tờ khai định kỳ."),
            (COLORS["warning"], "Kê khai  > 500tr",    "Hợp nhất phương pháp kê khai, tự tính và tự nộp qua mạng."),
            (COLORS["warning"], "Vượt ngưỡng 1 tỷ",   "Bắt buộc sử dụng HĐĐT khởi tạo từ máy tính tiền (POS)."),
            (COLORS["danger"],  "Hỗ trợ SME",          "Mô hình quy mô lớn được khuyến khích chuyển đổi lên Doanh nghiệp."),
            (COLORS["accent"],  "Miễn môn bài",        "Bãi bỏ hoàn toàn lệ phí môn bài cho HKD từ 01/01/2026."),
        ]
        for color, group, detail in rules_data:
            row = QHBoxLayout()
            row.setSpacing(12)
            dot = QLabel("●")
            dot.setFont(QFont("Segoe UI", 10))
            dot.setStyleSheet(f"color: {color}; background: transparent; border: none;")
            dot.setFixedWidth(14)
            g_lbl = QLabel(group)
            g_lbl.setFont(QFont("Segoe UI", 9, QFont.Weight.Bold))
            g_lbl.setStyleSheet("background: transparent; border: none;")
            g_lbl.setFixedWidth(160)
            d_lbl = QLabel(detail)
            d_lbl.setFont(QFont("Segoe UI", 9))
            d_lbl.setStyleSheet(f"color: {COLORS['text_secondary']}; background: transparent; border: none;")
            d_lbl.setWordWrap(True)
            row.addWidget(dot)
            row.addWidget(g_lbl)
            row.addWidget(d_lbl, stretch=1)
            rules_layout.addLayout(row)

        body_layout.addWidget(rules_frame)

        # -- (Deadline cards removed by user request) --


        body_layout.addStretch()
        scroll.setWidget(body)
        root.addWidget(scroll)

    # ── Data refresh ─────────────────────────────────────────
    def update_kpi(self, title, value):
        pass  # kept for compatibility

    def refresh(self, db_path: str = ""):
        """Load dữ liệu thực từ revenue DB."""
        try:
            from core.revenue_db import get_yearly_summary, get_daily_summary
            now = datetime.now()
            _db = db_path if db_path else None

            # Year total
            rev_stats  = get_yearly_summary(now.year, db_path=_db)
            total_rev  = rev_stats.get("total", 0)
            self.revenue_bar.update_revenue(total_rev)
            self.kpi_year.set_value(_fmt_vnd(total_rev))

            # Group classification
            if total_rev <= 500_000_000:
                self.kpi_group.set_value("Miễn thuế")
                self.kpi_group.set_accent(COLORS["success"])
            else:
                self.kpi_group.set_value("Tự kê khai")
                self.kpi_group.set_accent(COLORS["warning"])

            # Today
            today_str = now.strftime("%Y-%m-%d")
            day_data  = get_daily_summary(today_str, db_path=_db)
            entries   = day_data.get("entries", []) if isinstance(day_data, dict) else []
            thu_today = day_data.get("total_thu", 0) if isinstance(day_data, dict) else 0
            chi_today = day_data.get("total_chi", 0) if isinstance(day_data, dict) else 0
            # Fallback if daily_summary doesn't segregate
            if not thu_today and not chi_today:
                total_day = day_data.get("total", 0) if isinstance(day_data, dict) else 0
                self.kpi_thu.set_value(_fmt_vnd(total_day))
                self.kpi_chi.set_value("0 đ")
            else:
                self.kpi_thu.set_value(_fmt_vnd(thu_today))
                self.kpi_chi.set_value(_fmt_vnd(chi_today))

        except Exception as e:
            print(f"[Dashboard] Lỗi refresh: {e}")
