import json
import os
import time as time_module

import xbmc
import xbmcaddon
import xbmcgui
import xbmcvfs

from tools import debug_log


def handle_links_and_widgets(
    self,
    control_id,
    RemindersManager,
    browse_installed_video_addons,
    browse_addon_plugin_folders,
    import_channels_from_favourites,
    play_saved_jet_guide_link,
):
    if control_id == 111:  # Search Kodi Addons button
        selected_addon = browse_installed_video_addons()
        if not selected_addon:
            return True
        browse_addon_plugin_folders(selected_addon)
        return True

    if control_id == 112:  # Import Kodi Favourites button
        import_channels_from_favourites()
        return True

    if control_id == 113:  # Reminders dialog button
        manager = RemindersManager()
        options = ["Show Reminders", "Clear Reminders", "Remove Specific Reminder"]
        choice = xbmcgui.Dialog().select("Reminders", options)
        if choice == 0:
            reminders_text = manager.list_reminders()
            xbmcgui.Dialog().ok("Reminders", reminders_text)
        elif choice == 1:
            manager.clear_reminders()
            xbmcgui.Dialog().ok("Reminders", "All reminders have been cleared.")
        elif choice == 2:
            reminders = manager.load_reminders()
            if not reminders:
                xbmcgui.Dialog().ok("Reminders", "No reminders to remove.")
            else:
                display_list = [
                    f"{r['program']} on {r['channel']} at {time_module.strftime('%Y-%m-%d %H:%M', time_module.localtime(r['start_time']))}"
                    for r in reminders
                ]
                idx = xbmcgui.Dialog().select("Select Reminder to Remove", display_list)
                if idx != -1:
                    r = reminders[idx]
                    manager.remove_reminder(r["channel"], r["program"], r["start_time"])
                    xbmcgui.Dialog().ok("Reminders", "Selected reminder has been removed.")
        return True

    if control_id == 115:  # Browse Saved Links button
        folders_base_path = "special://userdata/addon_data/plugin.video.jet_guide/jet_guide_folders"
        folders_base = xbmcvfs.translatePath(folders_base_path)
        profile_path = xbmcvfs.translatePath(xbmcaddon.Addon().getAddonInfo('profile'))
        imported_path = profile_path + "jet_guide_imported.json"

        area_choice = xbmcgui.Dialog().select("Browse Links", ["Jet Guide Imported", "Saved Folders", "INFO"])
        if area_choice == 2:  # Directions
            readme_path = os.path.join(os.path.dirname(__file__), "README_tenbuttons_115.md")
            if os.path.exists(readme_path):
                with open(readme_path, "r", encoding="utf-8") as f:
                    directions = f.read()
                xbmcgui.Dialog().textviewer("Directions", directions)
            else:
                xbmcgui.Dialog().ok("Directions", "Directions file not found.")
            return True

        if area_choice == 0:  # Jet Guide Imported
            if xbmcvfs.exists(imported_path):
                with xbmcvfs.File(imported_path, 'r') as f:
                    imported = json.loads(f.read())
                if not imported:
                    xbmcgui.Dialog().ok('Jet Guide', 'No imported channels saved.')
                else:
                    titles = [c.get('title', 'Unknown') for c in imported]
                    idx = xbmcgui.Dialog().select('Play Imported Channel', titles)
                    if idx >= 0:
                        link = imported[idx].get('link')
                        action = xbmcgui.Dialog().select('Choose Action', ['Play', 'Delete', 'Move to Folder'])
                        if action == 0 and link:
                            xbmc.Player().play(link)
                        elif action == 1:
                            del imported[idx]
                            with xbmcvfs.File(imported_path, 'w') as f:
                                f.write(json.dumps(imported, indent=2))
                            xbmcgui.Dialog().ok('Jet Guide', 'Link deleted.')
                        elif action == 2:
                            folders_base = xbmcvfs.translatePath(folders_base_path)
                            try:
                                folders = [f for f in os.listdir(folders_base) if os.path.isdir(os.path.join(folders_base, f))]
                            except Exception as e:
                                debug_log(f"DEBUG: os.listdir failed for {folders_base}: {e}", level=xbmc.LOGERROR)
                                folders = []
                            if not folders:
                                xbmcgui.Dialog().ok('Jet Guide', 'No folders found.')
                            else:
                                folder_idx = xbmcgui.Dialog().select('Select Folder', folders)
                                if folder_idx >= 0:
                                    folder_path = os.path.join(folders_base, folders[folder_idx])
                                    links_file = os.path.join(folder_path, "links.json")
                                    if os.path.exists(links_file):
                                        with open(links_file, "r", encoding="utf-8") as f:
                                            folder_links = json.load(f)
                                    else:
                                        folder_links = []
                                    folder_links.append(imported[idx])
                                    with open(links_file, "w", encoding="utf-8") as f:
                                        json.dump(folder_links, f, indent=2)
                                    xbmcgui.Dialog().ok('Jet Guide', 'Link moved to folder.')
                                    del imported[idx]
                                    with xbmcvfs.File(imported_path, 'w') as f:
                                        f.write(json.dumps(imported, indent=2))
            else:
                xbmcgui.Dialog().ok('Jet Guide', 'No imported channels saved.')
            return True

        if area_choice == 1:  # Saved Folders
            try:
                folders = [f for f in os.listdir(folders_base) if os.path.isdir(os.path.join(folders_base, f))]
            except Exception as e:
                debug_log(f"DEBUG: os.listdir failed for {folders_base}: {e}", level=xbmc.LOGERROR)
                folders = []
            if not folders:
                xbmcgui.Dialog().ok('Jet Guide', 'No folders found.')
            else:
                folder_idx = xbmcgui.Dialog().select('Select Folder', folders)
                if folder_idx >= 0:
                    folder_path = os.path.join(folders_base, folders[folder_idx])
                    links_file = os.path.join(folder_path, "links.json")
                    if os.path.exists(links_file):
                        with open(links_file, "r", encoding="utf-8") as f:
                            links = json.load(f)
                        if not links:
                            xbmcgui.Dialog().ok('Jet Guide', 'No links found in folder.')
                        else:
                            titles = [c.get('title', 'Unknown') for c in links]
                            idx = xbmcgui.Dialog().select('Play Folder Link', titles)
                            if idx >= 0:
                                link = links[idx].get('link')
                                action = xbmcgui.Dialog().select('Choose Action', ['Play', 'Delete'])
                                if action == 0 and link:
                                    xbmc.Player().play(link)
                                elif action == 1:
                                    del links[idx]
                                    with open(links_file, "w", encoding="utf-8") as f:
                                        json.dump(links, f, indent=2)
                                    xbmcgui.Dialog().ok('Jet Guide', 'Link deleted.')
                    else:
                        xbmcgui.Dialog().ok('Jet Guide', 'No links.json found in folder.')
            return True

    if control_id == 210:
        if self.widget_list:
            item = self.widget_list.getSelectedItem()
            if item:
                widget_link = item.getProperty("widget_link")
                if widget_link:
                    play_saved_jet_guide_link(widget_link)
        return True

    return False
