"""Recordings screen — list MP3s, play, transcribe, summarize."""

from __future__ import annotations

import threading
from pathlib import Path

from PySide6.QtCore import QObject, Qt, Signal, Slot
from PySide6.QtWidgets import (
    QFrame,
    QHBoxLayout,
    QLabel,
    QPushButton,
    QSplitter,
    QTableWidget,
    QTableWidgetItem,
    QVBoxLayout,
    QWidget,
)

from meeting_helper.gui.widgets.media_player import MediaPlayerWidget
from meeting_helper.gui.widgets.transcript_view import TranscriptView


class _Worker(QObject):
    """Background worker for transcription/summarization."""
    finished = Signal(str, str)  # (result_text, error)

    def __init__(self, task: str, path: Path, config):
        super().__init__()
        self.task = task
        self.path = path
        self.config = config

    def run(self):
        try:
            if self.task == "transcribe":
                from meeting_helper.ai.client import transcribe_audio_file
                result = transcribe_audio_file(str(self.path), self.config)
                self.finished.emit(result, "")
            elif self.task == "summarize":
                import asyncio
                from meeting_helper.ai.client import summarize_transcript
                result = asyncio.run(summarize_transcript(str(self.path), self.config))
                self.finished.emit(result, "")
        except Exception as exc:
            self.finished.emit("", str(exc))


class RecordingsScreen(QWidget):
    """Browse recordings, play audio, transcribe and summarize."""

    def __init__(self, parent=None):
        super().__init__(parent)
        self._recordings_dir: Path | None = None
        self._current_mp3: Path | None = None
        self._config = None
        self._setup_ui()

    def _setup_ui(self):
        layout = QVBoxLayout(self)
        layout.setContentsMargins(30, 30, 30, 30)
        layout.setSpacing(15)

        # Header
        header_row = QHBoxLayout()
        header = QLabel("Recordings")
        header.setStyleSheet("font-size: 22px; font-weight: 600; color: #ffffff;")
        header_row.addWidget(header)
        header_row.addStretch()

        refresh_btn = QPushButton("Refresh")
        refresh_btn.setProperty("class", "secondary")
        refresh_btn.setStyleSheet("background-color: #2a2a2a; color: #d4d4d4; min-width: 70px;")
        refresh_btn.clicked.connect(self.refresh)
        header_row.addWidget(refresh_btn)
        layout.addLayout(header_row)

        # Splitter: table on top, detail on bottom
        splitter = QSplitter(Qt.Vertical)

        # Table
        self._table = QTableWidget()
        self._table.setColumnCount(3)
        self._table.setHorizontalHeaderLabels(["Name", "Duration", "Date"])
        self._table.setSelectionBehavior(QTableWidget.SelectRows)
        self._table.setSelectionMode(QTableWidget.SingleSelection)
        self._table.setAlternatingRowColors(True)
        self._table.verticalHeader().setVisible(False)
        self._table.horizontalHeader().setStretchLastSection(True)
        self._table.setColumnWidth(0, 350)
        self._table.setColumnWidth(1, 80)
        self._table.currentCellChanged.connect(self._on_selection_changed)
        splitter.addWidget(self._table)

        # Detail panel
        detail = QWidget()
        detail_layout = QVBoxLayout(detail)
        detail_layout.setContentsMargins(0, 10, 0, 0)

        # Action buttons
        btn_row = QHBoxLayout()
        self._transcribe_btn = QPushButton("Transcribe")
        self._transcribe_btn.setEnabled(False)
        self._transcribe_btn.clicked.connect(self._do_transcribe)
        btn_row.addWidget(self._transcribe_btn)

        self._summarize_btn = QPushButton("Summarize")
        self._summarize_btn.setEnabled(False)
        self._summarize_btn.clicked.connect(self._do_summarize)
        btn_row.addWidget(self._summarize_btn)

        self._status_label = QLabel("")
        self._status_label.setStyleSheet("color: #808080; font-size: 12px;")
        btn_row.addWidget(self._status_label)
        btn_row.addStretch()
        detail_layout.addLayout(btn_row)

        # Media player
        self._player = MediaPlayerWidget()
        detail_layout.addWidget(self._player)

        # Transcript viewer
        self._transcript_view = TranscriptView()
        detail_layout.addWidget(self._transcript_view, 1)

        splitter.addWidget(detail)
        splitter.setSizes([300, 400])
        layout.addWidget(splitter, 1)

    def set_config(self, config):
        """Set the AppConfig for transcription/summarization."""
        self._config = config

    def set_recordings_dir(self, path: Path):
        """Set recordings directory and load files."""
        self._recordings_dir = path
        self.refresh()

    def refresh(self):
        """Reload the recordings list."""
        self._table.setRowCount(0)
        if not self._recordings_dir or not self._recordings_dir.is_dir():
            return

        mp3s = sorted(self._recordings_dir.glob("*.mp3"), key=lambda p: p.stat().st_mtime, reverse=True)

        self._table.setRowCount(len(mp3s))
        for row, mp3 in enumerate(mp3s):
            # Name
            name_item = QTableWidgetItem(mp3.stem)
            name_item.setData(Qt.UserRole, str(mp3))
            name_item.setFlags(name_item.flags() & ~Qt.ItemIsEditable)
            self._table.setItem(row, 0, name_item)

            # Duration — read from MP3 metadata or show "—"
            duration_text = "—"
            try:
                import subprocess
                result = subprocess.run(
                    ["ffprobe", "-v", "quiet", "-show_entries", "format=duration",
                     "-of", "default=noprint_wrappers=1:nokey=1", str(mp3)],
                    capture_output=True, text=True, timeout=3,
                )
                if result.returncode == 0:
                    secs = float(result.stdout.strip())
                    mins, s = divmod(int(secs), 60)
                    hrs, mins = divmod(mins, 60)
                    duration_text = f"{hrs}:{mins:02d}:{s:02d}" if hrs else f"{mins}:{s:02d}"
            except Exception:
                pass
            dur_item = QTableWidgetItem(duration_text)
            dur_item.setFlags(dur_item.flags() & ~Qt.ItemIsEditable)
            self._table.setItem(row, 1, dur_item)

            # Date
            import time
            mtime = mp3.stat().st_mtime
            date_text = time.strftime("%Y-%m-%d %H:%M", time.localtime(mtime))
            date_item = QTableWidgetItem(date_text)
            date_item.setFlags(date_item.flags() & ~Qt.ItemIsEditable)
            self._table.setItem(row, 2, date_item)

            # Color rows that have transcript/summary
            has_transcript = mp3.with_suffix(".transcript.txt").exists()
            has_summary = mp3.with_suffix(".summary.txt").exists()
            if has_transcript:
                name_item.setForeground(Qt.green)

    def _on_selection_changed(self, row: int, col: int, prev_row: int, prev_col: int):
        if row < 0:
            return

        item = self._table.item(row, 0)
        if not item:
            return

        mp3_path = Path(item.data(Qt.UserRole))
        self._current_mp3 = mp3_path
        self._player.load(mp3_path)
        self._transcribe_btn.setEnabled(True)
        self._status_label.setText("")

        # Load transcript if exists
        transcript_path = mp3_path.with_suffix(".transcript.txt")
        summary_path = mp3_path.with_suffix(".summary.txt")

        if summary_path.exists():
            self._transcript_view.load_file(summary_path)
            self._summarize_btn.setEnabled(False)
        elif transcript_path.exists():
            self._transcript_view.load_file(transcript_path)
            self._summarize_btn.setEnabled(True)
        else:
            # Try .live.txt
            live_path = mp3_path.with_suffix(".live.txt")
            if live_path.exists():
                self._transcript_view.load_file(live_path)
            else:
                self._transcript_view.clear()
            self._summarize_btn.setEnabled(False)

    def _do_transcribe(self):
        if not self._current_mp3 or not self._config:
            return

        self._transcribe_btn.setEnabled(False)
        self._summarize_btn.setEnabled(False)
        self._status_label.setText("Transcribing...")
        self._status_label.setStyleSheet("color: #dcdcaa; font-size: 12px;")

        worker = _Worker("transcribe", self._current_mp3, self._config)
        worker.finished.connect(self._on_transcribe_done)

        thread = threading.Thread(target=worker.run, daemon=True)
        thread.start()
        self._active_worker = worker

    @Slot(str, str)
    def _on_transcribe_done(self, result: str, error: str):
        if error:
            self._status_label.setText(f"Error: {error}")
            self._status_label.setStyleSheet("color: #f14c4c; font-size: 12px;")
            self._transcribe_btn.setEnabled(True)
        else:
            self._status_label.setText("Transcription complete")
            self._status_label.setStyleSheet("color: #4ec9b0; font-size: 12px;")
            self._transcript_view.set_title("Transcript")
            self._transcript_view.set_text(result)
            self._summarize_btn.setEnabled(True)
            self._transcribe_btn.setEnabled(True)

    def _do_summarize(self):
        if not self._current_mp3 or not self._config:
            return

        transcript_path = self._current_mp3.with_suffix(".transcript.txt")
        if not transcript_path.exists():
            live_path = self._current_mp3.with_suffix(".live.txt")
            if live_path.exists():
                transcript_path = live_path
            else:
                self._status_label.setText("No transcript to summarize")
                return

        self._summarize_btn.setEnabled(False)
        self._status_label.setText("Summarizing...")
        self._status_label.setStyleSheet("color: #dcdcaa; font-size: 12px;")

        worker = _Worker("summarize", transcript_path, self._config)
        worker.finished.connect(self._on_summarize_done)

        thread = threading.Thread(target=worker.run, daemon=True)
        thread.start()
        self._active_worker = worker

    @Slot(str, str)
    def _on_summarize_done(self, result: str, error: str):
        if error:
            self._status_label.setText(f"Error: {error}")
            self._status_label.setStyleSheet("color: #f14c4c; font-size: 12px;")
            self._summarize_btn.setEnabled(True)
        else:
            self._status_label.setText("Summary complete")
            self._status_label.setStyleSheet("color: #4ec9b0; font-size: 12px;")
            self._transcript_view.set_title("Summary")
            self._transcript_view.set_text(result)
