"""
journal_module.py — Nhật Ký / Chứng Từ module
Hiển thị danh sách chứng từ, tìm kiếm, và nhập liệu.
"""
import os
import sys
from PySide6.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QLabel, QFrame,
    QTableWidget, QTableWidgetItem, QHeaderView, QPushButton,
    QLineEdit, QScrollArea, QGroupBox, QGridLayout, QComboBox,
    QDateEdit, QMessageBox, QSplitter
)
from PySide6.QtCore import Qt, QDate
from PySide6.QtGui import QFont, QColor

from gui.theme import COLORS


class JournalPage(QWidget):
    """Module Nhật Ký / Chứng Từ kế toán."""

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

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

        # ── Toolbar ────────────────────────────────────────
        toolbar = QWidget()
        toolbar.setMaximumHeight(60)
        t_layout = QHBoxLayout(toolbar)
        t_layout.setContentsMargins(16, 8, 16, 8)
        t_layout.setSpacing(10)

        self.search_input = QLineEdit()
        self.search_input.setPlaceholderText("🔍  Tìm chứng từ (mã số, mô tả, đối tác)...")
        self.search_input.setFixedHeight(36)
        self.search_input.setMinimumWidth(300)
        self.search_input.textChanged.connect(self._on_search_changed)

        btn_new = QPushButton("➕  Chứng từ mới")
        btn_new.setFixedHeight(36)
        btn_new.clicked.connect(self._on_new_voucher)

        btn_import = QPushButton("📥  Import Excel")
        btn_import.setObjectName("btn_secondary")
        btn_import.setFixedHeight(36)
        btn_import.clicked.connect(self._on_import)

        t_layout.addWidget(self.search_input, stretch=1)
        t_layout.addWidget(btn_new)
        t_layout.addWidget(btn_import)
        root.addWidget(toolbar)

        # ── Body ────────────────────────────────────────────
        body = QWidget()
        body_layout = QVBoxLayout(body)
        body_layout.setContentsMargins(16, 15, 16, 15)
        body_layout.setSpacing(15)

        # Summary cards
        self.stat_widgets = {}
        cards_row = QHBoxLayout()
        cards_row.setSpacing(15)
        for title_c, value, color in [
            ("📋 Tổng chứng từ", "0",   COLORS["text_primary"]),
            ("✅ Đã duyệt",      "0",   COLORS["success"]),
            ("⏳ Chờ duyệt",     "0",   COLORS["warning"]),
        ]:
            frame = QFrame()
            frame.setObjectName("stat_card")
            fl = QVBoxLayout(frame)
            fl.setContentsMargins(14, 10, 14, 10)
            lbl_t = QLabel(title_c)
            lbl_t.setObjectName("label_muted")
            lbl_v = QLabel(value)
            lbl_v.setFont(QFont("Segoe UI", 20, QFont.Weight.Bold))
            lbl_v.setStyleSheet(f"color: {color}; background: transparent;")
            fl.addWidget(lbl_t)
            fl.addWidget(lbl_v)
            cards_row.addWidget(frame)
            self.stat_widgets[title_c] = lbl_v
        body_layout.addLayout(cards_row)

        # Voucher table
        tbl_label = QLabel("Danh sách chứng từ")
        tbl_label.setFont(QFont("Segoe UI", 11, QFont.Weight.Bold))
        body_layout.addWidget(tbl_label)

        self.table = QTableWidget()
        self.table.setColumnCount(6)
        self.table.setHorizontalHeaderLabels([
            "Mã GD", "Ngày", "Đối tác / Mô tả", "Phân Loại", "Tiền Thu", "Tiền Chi"
        ])
        self.table.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeMode.Stretch)
        for col in [0, 1, 3, 4, 5]:
            self.table.horizontalHeader().setSectionResizeMode(col, QHeaderView.ResizeMode.ResizeToContents)
        self.table.verticalHeader().setVisible(False)
        self.table.setAlternatingRowColors(True)
        self.table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        self.table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
        self.table.setMinimumHeight(300)

        body_layout.addWidget(self.table)


        # Info note
        note = QLabel(
            "💡  Dữ liệu hiển thị được lấy trực tiếp từ cơ sở dữ liệu công ty. "
            "Sử dụng nút '📥 Import Excel' để nạp chứng từ hàng loạt."
        )
        note.setObjectName("label_muted")
        note.setWordWrap(True)
        note.setFont(QFont("Segoe UI", 9))
        body_layout.addWidget(note)

        body_layout.addStretch()
        root.addWidget(body)

    def _on_new_voucher(self):
        from gui.modules.voucher_entry_dialog import VoucherEntryDialog
        dlg = VoucherEntryDialog(parent=self)
        if dlg.exec():
            main = self.window()
            if hasattr(main, "current_db_path"):
                self.refresh(main.current_db_path)

    def _on_search_changed(self):
        """Lọc dữ liệu trên bảng khi người dùng nhập từ khóa."""
        text = self.search_input.text().lower()
        for i in range(self.table.rowCount()):
            match = False
            for j in range(self.table.columnCount()):
                item = self.table.item(i, j)
                if item and text in item.text().lower():
                    match = True
                    break
            self.table.setRowHidden(i, not match)

    def _on_import(self):
        from gui.modules.import_dialog import ImportDialog
        dlg = ImportDialog(self)
        dlg.exec()
        # Refresh current page is handled via global broadcast if dlg updates main
        # But for quick feedback, we can refresh here if the user didn't change DB path
        main = self.window()
        if hasattr(main, "current_db_path"):
            self.refresh(main.current_db_path)

    def refresh(self, db_path: str):
        """Load real journal data from DB."""
        if not db_path or not os.path.exists(db_path):
            return

        try:
            from core.ledger import get_journal, get_period_summary
            import datetime
            now = datetime.datetime.now()
            
            # 1. Update summary stats
            stats = get_period_summary(db_path, now.year, now.month)
            self.stat_widgets["📋 Tổng chứng từ"].setText(str(stats.get("voucher_count", 0)))
            self.stat_widgets["✅ Đã duyệt"].setText(str(stats.get("posted", 0)))
            self.stat_widgets["⏳ Chờ duyệt"].setText(str(stats.get("draft", 0)))

            # 2. Update table
            rows = get_journal(db_path, now.year, now.month)
            self.table.setRowCount(len(rows))
            
            for i, r in enumerate(rows):
                # Columns: "Mã GD", "Ngày", "Đối tác / Mô tả", "Phân Loại", "Tiền Thu", "Tiền Chi"
                
                self.table.setItem(i, 0, QTableWidgetItem(str(r.get("voucher_no", ""))))
                self.table.setItem(i, 1, QTableWidgetItem(str(r.get("voucher_date", ""))))
                self.table.setItem(i, 2, QTableWidgetItem(str(r.get("description", ""))))
                
                # We hide the concept of Nợ/Có. If it's a Revenue/Income type -> Tiền Thu. Expense -> Tiền Chi.
                # Simplified: if debit > 0 and account is 111 (Cash) -> it's Thu.
                # Here we just show the numbers without asking them to understand accounting.
                v_type = r.get("voucher_type", "")
                self.table.setItem(i, 3, QTableWidgetItem(
                    "💰 Thu Tiền (Bán)" if v_type == "HDXB" else ("📉 Chi Tiền (Mua)" if v_type == "HDMV" else "🔄 Khác")
                ))
                
                amt = r.get("debit", 0) or r.get("credit", 0)
                
                is_thu = v_type == "HDXB"
                item_thu = QTableWidgetItem(f"{amt:,.0f} đ" if is_thu else "-")
                if is_thu: item_thu.setForeground(QColor(COLORS["success"]))
                self.table.setItem(i, 4, item_thu)
                
                item_chi = QTableWidgetItem(f"{amt:,.0f} đ" if not is_thu else "-")
                if not is_thu: item_chi.setForeground(QColor(COLORS["danger"]))
                self.table.setItem(i, 5, item_chi)

        except Exception as e:
            print(f"Error refreshing journal: {e}")
