"""UI dialog for the Directory Indexer tool."""

from __future__ import annotations

import webbrowser
from pathlib import Path

from PySide6.QtCore import Qt
from PySide6.QtGui import QFont
from PySide6.QtWidgets import (
    QDialog,
    QFileDialog,
    QFrame,
    QHBoxLayout,
    QLabel,
    QLineEdit,
    QPushButton,
    QVBoxLayout,
)

from shotx.tools.indexer import generate_directory_index
from shotx.ui.theme import Theme


class DirectoryIndexerDialog(QDialog):
    """Modern dialog for generating directory HTML indexes."""

    def __init__(self, parent=None, initial_dir: str = "") -> None:
        super().__init__(parent)
        self.setWindowTitle("ShotX — Directory Indexer")

        # On GNOME/Wayland, the only native way to remove the Maximize
        # button is to make the dialog a fixed size.
        self.setFixedSize(650, 350)

        self.last_generated_path: Path | None = None

        # Unified Theme
        self._apply_theme()

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

        # 1. Directory Selection Section
        input_frame = QFrame()
        input_frame.setObjectName("GroupFrame")
        input_layout = QVBoxLayout(input_frame)
        input_layout.setContentsMargins(15, 15, 15, 15)
        input_layout.setSpacing(10)

        title_label = QLabel("Select Directory to Index:")
        title_label.setFont(QFont("Inter", 10, QFont.Weight.Bold))
        input_layout.addWidget(title_label)

        path_row = QHBoxLayout()
        self.path_input = QLineEdit(initial_dir)
        self.path_input.setPlaceholderText("e.g., /home/user/Pictures/Screenshots")
        path_row.addWidget(self.path_input)

        self.btn_browse = QPushButton("📁 Browse")
        self.btn_browse.setObjectName("ActionBtn")
        self.btn_browse.clicked.connect(self._on_browse)
        path_row.addWidget(self.btn_browse)

        input_layout.addLayout(path_row)
        layout.addWidget(input_frame)

        # 2. Action Section
        self.btn_generate = QPushButton("🚀 Generate Index.html")
        self.btn_generate.setObjectName("PrimaryBtn")
        self.btn_generate.clicked.connect(self._on_generate)
        self.btn_generate.setFixedHeight(40)
        self.btn_generate.setFont(QFont("Inter", 11, QFont.Weight.DemiBold))
        self.btn_generate.setCursor(Qt.CursorShape.PointingHandCursor)
        layout.addWidget(self.btn_generate)

        # 3. Status/Result Section
        # Pre-allocate vertical space so the window doesn't jerk/shrink when this appears/disappears
        self.status_label = QLabel("")
        self.status_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.status_label.setWordWrap(True)
        self.status_label.setMinimumHeight(40)
        layout.addWidget(self.status_label)

        self.btn_open = QPushButton("🌐 Open in Browser")
        self.btn_open.setObjectName("ActionBtn")
        self.btn_open.clicked.connect(self._on_open_browser)
        self.btn_open.setFixedHeight(40)  # Keep consistent height
        layout.addWidget(self.btn_open)

        # Initially hide the actual elements, but they take up space via QSizePolicy now
        self._reset_status()

    def _apply_theme(self) -> None:
        """Applies the ShotX global theme."""
        self.setStyleSheet(f"""
            QDialog {{
                background-color: {Theme.BASE_DARK};
            }}
            #GroupFrame {{
                background-color: {Theme.BASE_LIGHTER};
                border: 1px solid rgba(255, 255, 255, 0.1);
                border-radius: 8px;
            }}
            QLabel {{
                color: {Theme.TEXT_PRIMARY};
                font-weight: 500;
            }}
            QLineEdit {{
                background-color: {Theme.BASE_DARK};
                color: {Theme.TEXT_PRIMARY};
                border: 1px solid rgba(255, 255, 255, 0.1);
                border-radius: 4px;
                padding: 6px;
                font-family: 'Monospace', 'Cousine';
            }}
            QLineEdit:focus {{
                border: 1px solid {Theme.ACCENT_PURPLE};
            }}
            QPushButton {{
                background-color: {Theme.BASE_LIGHTER};
                color: {Theme.TEXT_PRIMARY};
                border: 1px solid rgba(255, 255, 255, 0.1);
                padding: 6px 12px;
                border-radius: 4px;
            }}
            QPushButton:hover {{
                background-color: rgba(255, 255, 255, 0.1);
            }}
            #ActionBtn {{
                background-color: {Theme.BASE_LIGHTER};
                color: {Theme.TEXT_PRIMARY};
                font-weight: bold;
                padding: 8px 16px;
            }}
            #PrimaryBtn {{
                background-color: {Theme.ACCENT_PURPLE};
                color: #ffffff;
                font-weight: bold;
                border: none;
                border-radius: 6px;
            }}
            #PrimaryBtn:hover {{
                opacity: 0.9;
            }}
            #SuccessLabel {{
                color: #a3be8c;
                font-weight: bold;
            }}
            #ErrorLabel {{
                color: #bf616a;
                font-weight: bold;
            }}
        """)

    def _on_browse(self) -> None:
        start_dir = self.path_input.text() or str(Path.home())
        directory = QFileDialog.getExistingDirectory(
            self, "Select Directory", start_dir,
            QFileDialog.Option.ShowDirsOnly | QFileDialog.Option.DontResolveSymlinks
        )
        if directory:
            self.path_input.setText(directory)
            self._reset_status()

    def _reset_status(self) -> None:
        self.status_label.setText("")     # Clear text instead of hiding
        self.status_label.setStyleSheet("") # Clear color
        self.btn_open.hide()
        self.last_generated_path = None

    def _on_generate(self) -> None:
        self._reset_status()

        target_dir = self.path_input.text().strip()
        if not target_dir:
            self._show_error("Please select a directory first.")
            return

        # Fix path expansion so ~/ works correctly
        expanded_target = str(Path(target_dir).expanduser().resolve())

        try:
            output_path = generate_directory_index(expanded_target)
            self.last_generated_path = output_path

            # Format nicely. If the user typed ~, don't blow it up to the full path
            # in the success label just for display, keep it clean.
            self.status_label.setText(f"✅ Successfully created:\n{output_path}")
            self.status_label.setObjectName("SuccessLabel")

            # Force stylesheet refresh for the dynamic objectName change
            self.status_label.style().unpolish(self.status_label)
            self.status_label.style().polish(self.status_label)

            self.status_label.show()
            self.btn_open.show()

        except Exception as e:
            self._show_error(f"Failed to generate index: {e}")

    def _show_error(self, message: str) -> None:
        self.status_label.setText(f"❌\n{message}")
        self.status_label.setObjectName("ErrorLabel")
        self.status_label.style().unpolish(self.status_label)
        self.status_label.style().polish(self.status_label)

    def _on_open_browser(self) -> None:
        if self.last_generated_path and self.last_generated_path.exists():
            webbrowser.open(self.last_generated_path.as_uri())
