from __future__ import annotations

from pathlib import Path

from PySide6.QtCore import Qt, QUrl, QEvent
from PySide6.QtGui import QDesktopServices
from PySide6.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QTableWidget, QTableWidgetItem,
    QAbstractItemView, QHeaderView, QPushButton, QMessageBox
)

from mi100.repository import Repo
from mi100.ui.delegates import RowTintDelegate

BTN_ORANGE = (
    "QPushButton{background:#FFD8A8;color:#8E6129;border:1px solid #E5BF90;"
    "border-radius:4px;padding:4px 10px;font-weight:600;}"
    "QPushButton:hover{background:#E5BF90;}"
)


class EmailHistoryTab(QWidget):
    def __init__(self, repo: Repo, client_id_provider, parent=None):
        super().__init__(parent)
        self.repo = repo
        self.client_id_provider = client_id_provider
        self._row_delegate = RowTintDelegate()
        self._action_holders: dict[int, QWidget] = {}

        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(8)
        self.table = QTableWidget(0, 6)
        self.table.setHorizontalHeaderLabels(['Коли', 'Документ', 'Кому', 'Тема', 'Файл', 'Дії'])
        self.table.verticalHeader().setVisible(False)
        self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table.setSelectionMode(QAbstractItemView.SingleSelection)
        self.table.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeToContents)
        self.table.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeToContents)
        self.table.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeToContents)
        self.table.horizontalHeader().setSectionResizeMode(3, QHeaderView.ResizeToContents)
        self.table.horizontalHeader().setSectionResizeMode(4, QHeaderView.Stretch)
        self.table.horizontalHeader().setSectionResizeMode(5, QHeaderView.ResizeToContents)
        self.table.setColumnWidth(3, 120)
        self.table.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.table.setItemDelegate(self._row_delegate)
        self.table.setMouseTracking(True)
        self.table.viewport().setMouseTracking(True)
        self.table.cellEntered.connect(self._on_hover_row)
        self.table.viewport().installEventFilter(self)
        layout.addWidget(self.table)

    def refresh(self) -> None:
        client_id = self.client_id_provider()
        self.table.setRowCount(0)
        self._action_holders.clear()
        if not client_id:
            return
        rows = self.repo.list_client_email_history(int(client_id))
        for row in rows:
            r = self.table.rowCount()
            self.table.insertRow(r)
            vals = [
                str(row.get('sent_at') or ''),
                str(row.get('doc_number') or ''),
                str(row.get('sent_to_email') or ''),
                str(row.get('subject_snapshot') or ''),
                Path(str(row.get('file_path') or '')).name,
            ]
            for c, value in enumerate(vals):
                item = QTableWidgetItem(value)
                item.setData(RowTintDelegate.ROLE_BG_KEY, 'blue')
                self.table.setItem(r, c, item)

            actions = QWidget()
            actions.setAttribute(Qt.WA_StyledBackground, True)
            actions.setStyleSheet('background:transparent; border:none;')
            hlay = QHBoxLayout(actions)
            hlay.setContentsMargins(0, 0, 0, 0)
            hlay.setSpacing(6)
            btn_open = QPushButton('Відкрити')
            btn_open.setFixedSize(74, 30)
            btn_open.setStyleSheet(BTN_ORANGE)
            btn_open.clicked.connect(lambda _=False, p=str(row.get('file_path') or ''): self._open_file(p))
            hlay.addWidget(btn_open)
            btn_delete = QPushButton('Видалити')
            btn_delete.setFixedSize(78, 30)
            btn_delete.setStyleSheet("QPushButton{background:#FFA8A8;color:#7C2D12;border:1px solid #E59494;border-radius:4px;padding:4px 10px;font-weight:600;}QPushButton:hover{background:#E59494;}")
            btn_delete.clicked.connect(lambda _=False, hid=int(row.get('id') or 0): self._delete_history(hid))
            hlay.addWidget(btn_delete)
            self.table.setCellWidget(r, 5, actions)
            self._action_holders[r] = actions
            self._apply_row_widget_bg(r, hovered=False)
        self.table.resizeRowsToContents()
        self.table.resizeColumnsToContents()
        self.table.setColumnWidth(3, max(110, min(150, self.table.columnWidth(3))))
        self.table.setColumnWidth(5, max(84, min(110, self.table.columnWidth(5))))

    def _delete_history(self, history_id: int) -> None:
        if not history_id:
            return
        res = QMessageBox.question(self, 'Видалення', 'Видалити цей запис з Email-історії?', QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if res != QMessageBox.Yes:
            return
        self.repo.delete_email_history(int(history_id))
        self.refresh()

    def _open_file(self, file_path: str) -> None:
        path = Path(file_path)
        if not path.exists():
            QMessageBox.warning(self, 'Файл не знайдено', 'Документ не знайдено на диску.')
            return
        QDesktopServices.openUrl(QUrl.fromLocalFile(str(path)))

    def eventFilter(self, obj, event):
        if obj is self.table.viewport() and event.type() == QEvent.Leave:
            self._row_delegate.set_hover_row(-1)
            for row in list(self._action_holders):
                self._apply_row_widget_bg(row, hovered=False)
            self.table.viewport().update()
        return super().eventFilter(obj, event)

    def _on_hover_row(self, row: int, _col: int) -> None:
        self._row_delegate.set_hover_row(row)
        for r in list(self._action_holders):
            self._apply_row_widget_bg(r, hovered=(r == row))
        self.table.viewport().update()

    def _apply_row_widget_bg(self, row: int, hovered: bool) -> None:
        holder = self._action_holders.get(row)
        if not holder:
            return
        bg = '#A0CFFF' if not hovered else '#8EBCEB'
        holder.setStyleSheet(f'background:{bg}; border:none;')
