"""
LyricsDrawer — Translucent Full Lyrics Panel with Click-to-Seek for Subify v3.0 Ultra
"""

import objc
import AppKit
from AppKit import (
    NSPanel, NSView, NSTextField, NSScrollView, NSTableView,
    NSTableColumn, NSTableCellView, NSVisualEffectView, NSVisualEffectMaterialHUDWindow,
    NSVisualEffectBlendingModeBehindWindow, NSVisualEffectStateActive,
    NSColor, NSFont, NSFontWeightBold, NSFontWeightMedium,
    NSWindowStyleMaskTitled, NSWindowStyleMaskClosable, NSWindowStyleMaskResizable,
    NSMakeRect, NSMakePoint, NSMakeSize, NSCenterTextAlignment, NSApp
)
from Foundation import NSObject
from player_manager import PlayerManager


class DrawerRowView(NSTableCellView):
    def initWithFrame_(self, frame):
        self = objc.super(DrawerRowView, self).initWithFrame_(frame)
        if self is None:
            return None
        return self


class LyricsDrawerController(NSObject):
    """Controller for the translucent Full Lyrics Drawer panel."""

    def initWithApp_(self, app):
        self = objc.super(LyricsDrawerController, self).init()
        if self is None:
            return None
        self._app = app
        self._window = None
        self._scroll_view = None
        self._table_view = None
        self._lyric_lines = []
        self._current_index = -1
        self._player_name = 'Spotify'
        return self

    def toggleWindow(self):
        if self._window and self._window.isVisible():
            self._window.orderOut_(None)
        else:
            self.showWindow()

    def showWindow(self):
        if self._window is None:
            self._create_window()

        self._window.deminiaturize_(None)
        self._window.makeKeyAndOrderFront_(None)
        NSApp.activateIgnoringOtherApps_(True)

    def updateLyrics_player_(self, lines, player_name='Spotify'):
        self._lyric_lines = lines if lines else []
        self._player_name = player_name
        if self._table_view:
            self._table_view.reloadData()

    def highlightLineIndex_(self, idx):
        if idx != self._current_index and 0 <= idx < len(self._lyric_lines):
            self._current_index = idx
            if self._table_view:
                self._table_view.reloadData()
                self._table_view.scrollRowToVisible_(idx)

    def _create_window(self):
        w, h = 420, 520

        window = NSPanel.alloc().initWithContentRect_styleMask_backing_defer_(
            NSMakeRect(150, 150, w, h),
            NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable,
            2,
            False
        )
        window.setTitle_('Subify Full Lyrics')
        window.setLevel_(3)  # Floating
        window.setOpaque_(False)
        window.setBackgroundColor_(NSColor.clearColor())
        window.setReleasedWhenClosed_(False)

        effect = NSVisualEffectView.alloc().initWithFrame_(NSMakeRect(0, 0, w, h))
        effect.setMaterial_(NSVisualEffectMaterialHUDWindow)
        effect.setBlendingMode_(NSVisualEffectBlendingModeBehindWindow)
        effect.setState_(NSVisualEffectStateActive)
        effect.setAutoresizingMask_(AppKit.NSViewWidthSizable | AppKit.NSViewHeightSizable)
        window.setContentView_(effect)

        # Scroll view + Table View
        scroll = NSScrollView.alloc().initWithFrame_(NSMakeRect(15, 15, w - 30, h - 50))
        scroll.setDrawsBackground_(False)
        scroll.setHasVerticalScroller_(True)
        scroll.setAutoresizingMask_(AppKit.NSViewWidthSizable | AppKit.NSViewHeightSizable)

        table = NSTableView.alloc().initWithFrame_(scroll.bounds())
        table.setHeaderView_(None)
        table.setBackgroundColor_(NSColor.clearColor())

        column = NSTableColumn.alloc().initWithIdentifier_('LyricsColumn')
        column.setWidth_(w - 50)
        table.addTableColumn_(column)

        table.setDataSource_(self)
        table.setDelegate_(self)
        table.setTarget_(self)
        table.setDoubleAction_('rowDoubleClicked:')

        scroll.setDocumentView_(table)
        effect.addSubview_(scroll)

        self._scroll_view = scroll
        self._table_view = table
        self._window = window

    # ── NSTableView DataSource & Delegate ──

    def numberOfRowsInTableView_(self, table_view):
        return len(self._lyric_lines)

    def tableView_viewForTableColumn_row_(self, table_view, table_column, row):
        cell = table_view.makeViewWithIdentifier_owner_('LyricCell', self)
        if cell is None:
            cell = DrawerRowView.alloc().initWithFrame_(NSMakeRect(0, 0, 380, 28))
            cell.setIdentifier_('LyricCell')

            lbl = NSTextField.alloc().initWithFrame_(NSMakeRect(10, 2, 360, 24))
            lbl.setEditable_(False)
            lbl.setBezeled_(False)
            lbl.setDrawsBackground_(False)
            lbl.setSelectable_(False)
            lbl.setAutoresizingMask_(AppKit.NSViewWidthSizable)
            cell.addSubview_(lbl)
            cell.textField = lbl

        line = self._lyric_lines[row]
        lbl = cell.textField

        is_active = (row == self._current_index)
        font_weight = NSFontWeightBold if is_active else NSFontWeightMedium
        lbl.setFont_(NSFont.systemFontOfSize_weight_(15 if is_active else 13, font_weight))

        if is_active:
            lbl.setTextColor_(NSColor.colorWithRed_green_blue_alpha_(0.3, 0.9, 1.0, 1.0))
            lbl.setStringValue_(f"▶ {line.text}")
        else:
            lbl.setTextColor_(NSColor.colorWithWhite_alpha_(0.85, 0.85))
            lbl.setStringValue_(line.text)

        return cell

    def tableView_heightOfRow_(self, table_view, row):
        return 30.0

    @objc.IBAction
    def rowDoubleClicked_(self, sender):
        row = sender.clickedRow()
        if 0 <= row < len(self._lyric_lines):
            line = self._lyric_lines[row]
            PlayerManager.seek(line.timestamp, self._player_name)
