import random
import re

import requests
import xbmc
import xbmcgui

from endpoints import MUSIC_BASE_DIR
from tools import debug_log


def handle_window_click_actions(self, control_id):
    if control_id == 130:  # Picture-in-Picture / Now Playing button
        debug_log("DEBUG: Button 130 clicked!", level=xbmc.LOGINFO)
        player = xbmc.Player()
        if player.isPlaying():
            debug_log("DEBUG: Video is playing, attempting fullscreen", level=xbmc.LOGINFO)
            xbmc.executebuiltin('Dialog.Close(all,true)')
            xbmc.sleep(200)
            xbmc.executebuiltin('Action(FullScreen)')
            xbmc.sleep(100)
        else:
            debug_log("DEBUG: No video playing, closing dialogs only", level=xbmc.LOGINFO)
            xbmc.executebuiltin('Dialog.Close(all,true)')
        return True

    if control_id == 114:  # Exit button
        xbmc.executebuiltin('Dialog.Close(all)')
        self.close()
        xbmc.executebuiltin('ActivateWindow(Home)')
        return True

    if control_id == 200:  # Last Watched List
        if self.last_watched_list:
            item = self.last_watched_list.getSelectedItem()
            if item:
                channel_id = item.getProperty('channel_id')
                if channel_id:
                    self.play_last_watched(channel_id)
        return True

    if control_id == 362:  # Last Watched Preview List (EPG context)
        preview_list = getattr(self, 'last_watched_preview_list', None)
        if preview_list:
            item = preview_list.getSelectedItem()
            if item:
                channel_id = item.getProperty('channel_id')
                if channel_id:
                    self.play_last_watched(channel_id)
        return True

    if control_id == 365:  # Favorites Preview List
        preview_list = getattr(self, 'favorites_preview_list', None)
        if preview_list:
            item = preview_list.getSelectedItem()
            if item:
                channel_id = item.getProperty('channel_id')
                if channel_id:
                    self.play_last_watched(channel_id)
        return True

    if control_id == 960:  # YouTube Genre Channels button
        base_url = MUSIC_BASE_DIR
        try:
            resp = requests.get(base_url)
            files = re.findall(r'href="([^"]+\.json)"', resp.text)
            if not files:
                xbmcgui.Dialog().ok("YouTube Genre Channels", "No JSON files found at remote address.")
                return True
            file_idx = xbmcgui.Dialog().select("Select Music Channel JSON", files)
            if file_idx == -1:
                return True
            json_url = base_url + files[file_idx]
            data = requests.get(json_url).json()
        except Exception as e:
            xbmcgui.Dialog().ok("Error", f"Failed to fetch JSON list or file: {e}")
            return True

        genre_map = {}
        for item in data.get("items", []):
            match = re.search(r"Genre:\s*([^\n]+)", item.get("summary", ""))
            genres = [g.strip() for g in match.group(1).split(",")] if match else ["Unknown"]
            for genre in genres:
                genre_map.setdefault(genre, []).append(item)

        genre_list = sorted(genre_map.keys())
        genre_idx = xbmcgui.Dialog().select("Select Genre Channel", genre_list)
        if genre_idx == -1:
            return True
        selected_genre = genre_list[genre_idx]
        videos = genre_map[selected_genre]

        play_mode = xbmcgui.Dialog().select(
            "Playback Mode",
            ["Play All (Random Order, May Crash)", "Play One Random Song (Recommended)"],
        )
        if play_mode == -1:
            return True

        if play_mode == 1:
            vid = random.choice(videos)
            listitem = xbmcgui.ListItem(label=vid["title"])
            if vid.get("thumbnail"):
                listitem.setArt({'thumb': vid["thumbnail"]})
            match = re.search(r"(?:v=|youtu\.be/)([A-Za-z0-9_-]{11})", vid["link"])
            youtube_url = f"plugin://plugin.video.youtube/play/?video_id={match.group(1)}" if match else vid["link"]
            xbmc.Player().play(youtube_url, listitem)
            xbmcgui.Dialog().ok(
                "YouTube Plugin Notice",
                "Single random song played. Continuous playback is unstable due to Kodi/YouTube plugin limitations. For best results, use this mode or create a YouTube playlist in your browser and play it in Kodi.",
            )
            return True

        xbmcgui.Dialog().ok(
            "YouTube Plugin Notice",
            "Continuous playback of YouTube plugin videos in Kodi is unstable and may crash or skip tracks. For best results, use 'Play One Random Song' or create a playlist on YouTube and play it in Kodi.",
        )
        playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
        playlist.clear()
        random.shuffle(videos)
        xbmc.sleep(2000)
        for vid in videos:
            listitem = xbmcgui.ListItem(label=vid["title"])
            if vid.get("thumbnail"):
                listitem.setArt({'thumb': vid["thumbnail"]})
            match = re.search(r"(?:v=|youtu\.be/)([A-Za-z0-9_-]{11})", vid["link"])
            youtube_url = f"plugin://plugin.video.youtube/play/?video_id={match.group(1)}" if match else vid["link"]
            playlist.add(youtube_url, listitem)
        xbmc.Player().play(playlist)
        return True

    return False
