# -*- coding: utf-8 -*-
"""Welcome page shown before a project is opened."""

from util.runtime import *
from util.recent_projects import load_recent_projects
from views.common import apply_button_style, make_line_icon, set_button_icon

class WelcomePage(QWidget):
    """欢迎页：未打开项目时显示，提供“打开项目”“帮助”和“最近项目”"""
    open_project_requested = pyqtSignal(object)  # Path or str
    help_requested = pyqtSignal()  # 点击“帮助”时发出，主窗口弹出帮助菜单
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self._build_ui()
    
    def _build_ui(self):
        layout = QVBoxLayout(self)
        layout.setSpacing(16)
        layout.setContentsMargins(10, 8, 10, 10)

        self.setStyleSheet("""
            QFrame#welcomeCard, QFrame#recentCard {
                background-color: #242932;
                border: 1px solid #3a4352;
                border-radius: 8px;
            }
            QLabel#welcomeIcon {
                background-color: #243247;
                color: #4f8cff;
                border-radius: 24px;
                font-size: 28px;
            }
            QLabel#welcomeTitle {
                color: #e8eef7;
                font-size: 20px;
                font-weight: 700;
            }
            QLabel#welcomeSubtitle {
                color: #aab4c3;
                font-size: 13px;
            }
            QLabel#recentTitle {
                color: #e8eef7;
                font-size: 14px;
                font-weight: 600;
            }
            QFrame#recentRow {
                background-color: #242932;
                border: 1px solid #343d4c;
                border-radius: 0px;
            }
            QFrame#recentRow:hover {
                background-color: #2b313c;
            }
            QLabel#pathText {
                color: #e8eef7;
                font-size: 12px;
            }
            QLabel#folderIcon {
                color: #4f8cff;
                font-size: 18px;
            }
        """)
        
        # 顶部打开项目卡片
        welcome_card = QFrame()
        welcome_card.setObjectName("welcomeCard")
        welcome_card.setMinimumHeight(200)
        welcome_layout = QVBoxLayout(welcome_card)
        welcome_layout.setContentsMargins(24, 18, 24, 22)
        welcome_layout.setSpacing(12)
        welcome_layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
        
        icon = QLabel()
        icon.setObjectName("welcomeIcon")
        icon.setFixedSize(48, 48)
        icon.setAlignment(Qt.AlignmentFlag.AlignCenter)
        icon.setPixmap(make_line_icon("folder", "#4f8cff", 28).pixmap(28, 28))
        welcome_layout.addWidget(icon, alignment=Qt.AlignmentFlag.AlignCenter)
        
        title = QLabel("打开服务器项目")
        title.setObjectName("welcomeTitle")
        title.setAlignment(Qt.AlignmentFlag.AlignCenter)
        welcome_layout.addWidget(title)
        
        subtitle = QLabel("请选择一个已有服务器项目目录，或从最近项目中快速进入")
        subtitle.setObjectName("welcomeSubtitle")
        subtitle.setAlignment(Qt.AlignmentFlag.AlignCenter)
        welcome_layout.addWidget(subtitle)
        
        btn_row = QHBoxLayout()
        btn_row.setSpacing(12)
        btn_row.setAlignment(Qt.AlignmentFlag.AlignCenter)
        btn_open = QPushButton("打开项目")
        btn_open.setFixedSize(112, 34)
        apply_button_style(btn_open, "primary")
        set_button_icon(btn_open, "folder", "#242932", 16)
        btn_open.clicked.connect(self._on_open_project)

        btn_new = QPushButton("新建项目")
        btn_new.setFixedSize(112, 34)
        apply_button_style(btn_new, "outline")
        set_button_icon(btn_new, "plus", "#4f8cff", 16)
        btn_new.clicked.connect(self._on_open_project)

        btn_help = QPushButton("帮助")
        btn_help.setFixedSize(106, 34)
        apply_button_style(btn_help, "neutral")
        set_button_icon(btn_help, "help", "#aab4c3", 16)
        btn_help.clicked.connect(self.help_requested.emit)
        btn_row.addWidget(btn_open)
        btn_row.addWidget(btn_new)
        btn_row.addWidget(btn_help)
        welcome_layout.addLayout(btn_row)
        layout.addWidget(welcome_card)
        
        # 最近项目卡片
        recent_card = QFrame()
        recent_card.setObjectName("recentCard")
        recent_layout = QVBoxLayout(recent_card)
        recent_layout.setContentsMargins(16, 14, 16, 16)
        recent_layout.setSpacing(12)

        recent_title = QLabel("最近项目")
        recent_title.setObjectName("recentTitle")
        recent_header = QHBoxLayout()
        recent_header.setSpacing(8)
        recent_icon = QLabel()
        recent_icon.setPixmap(make_line_icon("calendar", "#4f8cff", 18).pixmap(18, 18))
        recent_header.addWidget(recent_icon)
        recent_header.addWidget(recent_title)
        recent_header.addStretch()
        recent_layout.addLayout(recent_header)
        
        self.recent_rows = QWidget()
        self.recent_rows_layout = QVBoxLayout(self.recent_rows)
        self.recent_rows_layout.setContentsMargins(0, 0, 0, 0)
        self.recent_rows_layout.setSpacing(0)
        recent_layout.addWidget(self.recent_rows)

        more_btn = QPushButton("浏览更多项目目录...")
        set_button_icon(more_btn, "folder", "#4f8cff", 15)
        more_btn.setFlat(True)
        more_btn.setCursor(Qt.CursorShape.PointingHandCursor)
        more_btn.setStyleSheet("""
            QPushButton {
                background-color: transparent;
                color: #4f8cff;
                border: none;
                padding: 4px 8px;
                font-size: 13px;
                font-weight: 600;
            }
            QPushButton:hover {
                color: #3f7df0;
                text-decoration: underline;
            }
        """)
        more_btn.clicked.connect(self._on_open_project)
        recent_layout.addWidget(more_btn, alignment=Qt.AlignmentFlag.AlignCenter)

        layout.addWidget(recent_card)
        
        layout.addStretch()
        self._refresh_recent()
    
    def _refresh_recent(self):
        while self.recent_rows_layout.count():
            item = self.recent_rows_layout.takeAt(0)
            if item.widget():
                item.widget().deleteLater()

        recent = load_recent_projects()
        if not recent:
            empty = QLabel("暂无最近项目")
            empty.setStyleSheet("color: #778398; padding: 12px;")
            empty.setAlignment(Qt.AlignmentFlag.AlignCenter)
            self.recent_rows_layout.addWidget(empty)
            return

        for index, path in enumerate(recent[:5]):
            self.recent_rows_layout.addWidget(self._create_recent_row(path, index, len(recent[:5])))

    def _create_recent_row(self, path: str, index: int, total: int) -> QWidget:
        row = QFrame()
        row.setObjectName("recentRow")
        if total == 1:
            radius = "8px"
        elif index == 0:
            radius = "8px 8px 0px 0px"
        elif index == total - 1:
            radius = "0px 0px 8px 8px"
        else:
            radius = "0px"
        row.setStyleSheet(f"""
            QFrame#recentRow {{
                background-color: #242932;
                border: 1px solid #343d4c;
                border-radius: {radius};
            }}
            QFrame#recentRow:hover {{
                background-color: #2b313c;
            }}
        """)
        row_layout = QHBoxLayout(row)
        row_layout.setContentsMargins(12, 7, 10, 7)
        row_layout.setSpacing(10)

        icon = QLabel()
        icon.setObjectName("folderIcon")
        icon.setFixedWidth(20)
        icon.setPixmap(make_line_icon("folder", "#4f8cff", 18).pixmap(18, 18))
        row_layout.addWidget(icon)

        path_label = QLabel(path)
        path_label.setObjectName("pathText")
        path_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
        row_layout.addWidget(path_label, 1)

        open_btn = QPushButton("打开")
        open_btn.setFixedSize(48, 28)
        apply_button_style(open_btn, "outline", compact=True)
        set_button_icon(open_btn, "folder", "#4f8cff", 14)
        open_btn.clicked.connect(lambda checked=False, p=path: self.open_project_requested.emit(Path(p)))
        row_layout.addWidget(open_btn)

        locate_btn = QPushButton("定位")
        locate_btn.setFixedSize(48, 28)
        apply_button_style(locate_btn, "neutral", compact=True)
        set_button_icon(locate_btn, "external", "#aab4c3", 14)
        locate_btn.clicked.connect(lambda checked=False, p=path: self._locate_project(p))
        row_layout.addWidget(locate_btn)
        return row
    
    def _on_open_project(self):
        from PyQt6.QtWidgets import QFileDialog
        path = QFileDialog.getExistingDirectory(self, "选择服务器项目目录", str(Path.cwd()))
        if path:
            self.open_project_requested.emit(Path(path))
    
    def _on_recent_double_clicked(self, item):
        path = item.text().strip()
        if path and Path(path).exists():
            self.open_project_requested.emit(Path(path))

    def _locate_project(self, path: str):
        target = Path(path)
        try:
            if IS_WINDOWS:
                subprocess.Popen(["explorer", str(target)])
            else:
                subprocess.Popen(["xdg-open", str(target)])
        except Exception as e:
            QMessageBox.warning(self, "定位项目", f"无法打开目录：{e}")
    
    def showEvent(self, event):
        super().showEvent(event)
        self._refresh_recent()
