from __future__ import annotations

from PyQt6.QtCore import Qt
from PyQt6.QtGui import QAction
from PyQt6.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, QProgressBar,
    QTextEdit, QMessageBox, QComboBox, QLineEdit, QFormLayout, QToolButton, QMenu
)

from ..core.settings import load_config, save_config, AppConfig


class LoadingPage(QWidget):
    def __init__(self):
        super().__init__()
        layout = QVBoxLayout(self)
        layout.setAlignment(Qt.AlignmentFlag.AlignCenter)

        self.title = QLabel("Loading resources…")
        self.title.setAlignment(Qt.AlignmentFlag.AlignCenter)

        self.progress = QProgressBar()
        self.progress.setRange(0, 0)

        self.hint = QLabel("This may take a while the first time (Whisper model download).")
        self.hint.setAlignment(Qt.AlignmentFlag.AlignCenter)

        layout.addWidget(self.title)
        layout.addWidget(self.progress)
        layout.addWidget(self.hint)


class HomePage(QWidget):
    upload_clicked = None
    record_clicked = None
    settings_clicked = None

    rec_pause_clicked = None
    rec_resume_clicked = None
    rec_stop_clicked = None
    rec_play_clicked = None
    rec_save_clicked = None
    rec_discard_clicked = None

    def __init__(self):
        super().__init__()
        self.upload_clicked = lambda: None
        self.record_clicked = lambda: None
        self.settings_clicked = lambda: None

        self.rec_pause_clicked = lambda: None
        self.rec_resume_clicked = lambda: None
        self.rec_stop_clicked = lambda: None
        self.rec_play_clicked = lambda: None
        self.rec_save_clicked = lambda: None
        self.rec_discard_clicked = lambda: None

        layout = QVBoxLayout(self)
        layout.setAlignment(Qt.AlignmentFlag.AlignTop)
        layout.setSpacing(14)

        header = QHBoxLayout()
        self.settings_btn = QPushButton("Settings")
        self.settings_btn.clicked.connect(lambda: self.settings_clicked())
        header.addStretch(1)
        header.addWidget(self.settings_btn)

        # Side-by-side buttons
        self.upload_btn = QPushButton("Upload audio/video")
        self.record_btn = QPushButton("Record audio")
        for b in (self.upload_btn, self.record_btn):
            b.setMinimumHeight(44)
            b.setMaximumWidth(240)

        self.upload_btn.clicked.connect(lambda: self.upload_clicked())
        self.record_btn.clicked.connect(lambda: self.record_clicked())

        main_row = QHBoxLayout()
        main_row.addWidget(self.upload_btn)
        main_row.addWidget(self.record_btn)
        main_row.addStretch(1)

        # Recording panel (hidden by default)
        self.rec_panel = QWidget()
        rec_layout = QVBoxLayout(self.rec_panel)
        rec_layout.setContentsMargins(0, 0, 0, 0)
        rec_layout.setSpacing(10)

        self.rec_status = QLabel("")
        self.rec_status.setWordWrap(True)

        rec_buttons = QHBoxLayout()
        self.pause_btn = QPushButton("Pause")
        self.resume_btn = QPushButton("Resume")
        self.stop_btn = QPushButton("Stop")
        self.play_btn = QPushButton("Play")
        self.save_btn = QPushButton("Save & Transcribe")
        self.discard_btn = QPushButton("Discard")

        for b in (self.pause_btn, self.resume_btn, self.stop_btn, self.play_btn, self.save_btn, self.discard_btn):
            b.setMinimumHeight(40)

        self.pause_btn.clicked.connect(lambda: self.rec_pause_clicked())
        self.resume_btn.clicked.connect(lambda: self.rec_resume_clicked())
        self.stop_btn.clicked.connect(lambda: self.rec_stop_clicked())
        self.play_btn.clicked.connect(lambda: self.rec_play_clicked())
        self.save_btn.clicked.connect(lambda: self.rec_save_clicked())
        self.discard_btn.clicked.connect(lambda: self.rec_discard_clicked())

        rec_buttons.addWidget(self.pause_btn)
        rec_buttons.addWidget(self.resume_btn)
        rec_buttons.addWidget(self.stop_btn)
        rec_buttons.addWidget(self.play_btn)
        rec_buttons.addWidget(self.save_btn)
        rec_buttons.addWidget(self.discard_btn)
        rec_buttons.addStretch(1)

        rec_layout.addWidget(self.rec_status)
        rec_layout.addLayout(rec_buttons)
        self.rec_panel.setVisible(False)

        self.results_label = QLabel("")
        self.results_label.setWordWrap(True)

        self.text_box = QTextEdit()
        self.text_box.setReadOnly(False)
        self.text_box.setVisible(False)

        actions = QHBoxLayout()
        self.copy_btn = QPushButton("Copy")
        self.download_btn = QToolButton()
        self.download_btn.setText("Download")
        self.download_btn.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup)
        self.copy_btn.setVisible(False)
        self.download_btn.setVisible(False)

        menu = QMenu(self.download_btn)
        self.act_txt = QAction("TXT", self)
        self.act_pdf = QAction("PDF", self)
        self.act_docx = QAction("Word (DOCX)", self)
        menu.addAction(self.act_txt)
        menu.addAction(self.act_pdf)
        menu.addAction(self.act_docx)
        self.download_btn.setMenu(menu)

        actions.addWidget(self.copy_btn)
        actions.addWidget(self.download_btn)
        actions.addStretch(1)

        layout.addLayout(header)
        layout.addLayout(main_row)
        layout.addWidget(self.rec_panel)
        layout.addWidget(self.results_label)
        layout.addWidget(self.text_box)
        layout.addLayout(actions)
        layout.addStretch(1)

        self._set_rec_state("idle")

    def _set_rec_state(self, state: str) -> None:
        if state == "idle":
            self.rec_panel.setVisible(False)
            self.upload_btn.setVisible(True)
            self.record_btn.setVisible(True)
            return

        self.rec_panel.setVisible(True)
        self.upload_btn.setVisible(False)
        self.record_btn.setVisible(False)

        if state == "recording":
            self.pause_btn.setEnabled(True)
            self.resume_btn.setEnabled(False)
            self.stop_btn.setEnabled(True)
            self.play_btn.setEnabled(False)
            self.save_btn.setEnabled(False)
        elif state == "paused":
            self.pause_btn.setEnabled(False)
            self.resume_btn.setEnabled(True)
            self.stop_btn.setEnabled(True)
            self.play_btn.setEnabled(True)
            self.save_btn.setEnabled(False)
        elif state == "stopped":
            self.pause_btn.setEnabled(False)
            self.resume_btn.setEnabled(False)
            self.stop_btn.setEnabled(False)
            self.play_btn.setEnabled(True)
            self.save_btn.setEnabled(True)

    def enter_recording_mode(self) -> None:
        self.rec_status.setText("Recording…")
        self._set_rec_state("recording")

    def set_paused(self) -> None:
        self.rec_status.setText("Recording paused.")
        self._set_rec_state("paused")

    def set_recording(self) -> None:
        self.rec_status.setText("Recording…")
        self._set_rec_state("recording")

    def set_stopped(self) -> None:
        self.rec_status.setText("Recording stopped. You can play it back or save it.")
        self._set_rec_state("stopped")

    def exit_recording_mode(self) -> None:
        self.rec_status.setText("")
        self._set_rec_state("idle")

    def show_results(self, text: str) -> None:
        self.text_box.setPlainText(text)
        self.text_box.setVisible(True)
        self.copy_btn.setVisible(True)
        self.download_btn.setVisible(True)
        self.results_label.setText("Transcription ready.")


class SettingsPage(QWidget):
    back_clicked = None

    def __init__(self):
        super().__init__()
        self.back_clicked = lambda: None

        layout = QVBoxLayout(self)
        top = QHBoxLayout()
        self.back_btn = QPushButton("← Home")
        self.back_btn.clicked.connect(lambda: self.back_clicked())
        top.addWidget(self.back_btn)
        top.addStretch(1)

        form = QFormLayout()
        self.model_dir = QLineEdit()
        self.browse_btn = QPushButton("Browse…")
        row = QHBoxLayout()
        row.addWidget(self.model_dir, 1)
        row.addWidget(self.browse_btn)

        self.model_size = QComboBox()
        self.model_size.addItems(["tiny", "base", "small", "medium", "large"])

        self.language = QLineEdit()
        self.language.setPlaceholderText("Optional (e.g. en). Leave empty for auto.")

        self.task = QComboBox()
        self.task.addItems(["transcribe", "translate"])

        form.addRow("Model directory:", row)
        form.addRow("Model size:", self.model_size)
        form.addRow("Language:", self.language)
        form.addRow("Task:", self.task)

        self.save_btn = QPushButton("Save settings")

        layout.addLayout(top)
        layout.addSpacing(8)
        layout.addLayout(form)
        layout.addSpacing(10)
        layout.addWidget(self.save_btn)
        layout.addStretch(1)

        self.browse_btn.clicked.connect(self._browse)
        self.save_btn.clicked.connect(self._save)
        self._load()

    def _browse(self) -> None:
        from PyQt6.QtWidgets import QFileDialog
        directory = QFileDialog.getExistingDirectory(self, "Select model directory")
        if directory:
            self.model_dir.setText(directory)

    def _load(self) -> None:
        cfg = load_config()
        self.model_dir.setText(cfg.model_dir)
        idx = self.model_size.findText(cfg.model_size)
        if idx >= 0:
            self.model_size.setCurrentIndex(idx)
        self.language.setText(cfg.language or "")
        idx = self.task.findText(cfg.task)
        if idx >= 0:
            self.task.setCurrentIndex(idx)

    def _save(self) -> None:
        cfg = AppConfig(
            model_dir=self.model_dir.text().strip(),
            model_size=self.model_size.currentText(),  # type: ignore[arg-type]
            language=(self.language.text().strip() or None),
            task=self.task.currentText(),              # type: ignore[arg-type]
        )
        save_config(cfg)
        QMessageBox.information(self, "Saved", "Settings saved.")
