import xbmc
import xbmcgui


def handle_basic_button_actions(
    self,
    control_id,
    parse_m3u8,
    parse_xmltv,
    m3u8_path,
    xmltv_path,
    addon,
    favorites_manager,
    SearchWindow,
    show_sports_guide,
    show_sports_grid,
):
    """Handle basic TenButtons control IDs (101,102,104,105,106,108)."""
    if control_id == 101:  # Button 1 - Show EPG Grid
        from epggrid import EPGGrid
        progress = xbmcgui.DialogProgress()
        progress.create('Loading TV Guide', 'Starting...')
        progress.update(0)

        def progress_cb(percent, message):
            try:
                progress.update(max(0, min(100, int(percent))), message)
            except Exception:
                pass

        try:
            channels = parse_m3u8(m3u8_path, progress_cb=progress_cb)
            programs = parse_xmltv(xmltv_path, progress_cb=progress_cb)
            progress.update(94, 'Preparing guide...')
            addon_path = addon.getAddonInfo('path')
            xml_file = 'tuepg.guide.experimental.xml'
            epg_window = EPGGrid(xml_file, addon_path, channels=channels, programs=programs)
            progress.update(100, 'Opening guide...')
            progress.close()
            epg_window.doModal()
            del epg_window
        except Exception as e:
            progress.close()
            xbmcgui.Dialog().ok("Error", f"Failed to load TV Guide: {str(e)}")
        return True

    if control_id == 102:  # Button 2 - Show Sports Events
        progress = xbmcgui.DialogProgress()
        progress.create('Loading Sports Guide', 'Starting...')
        progress.update(0)
        try:
            def sports_progress_cb(percent, message):
                try:
                    progress.update(max(0, min(100, int(percent))), message)
                except Exception:
                    pass

            progress.update(5, 'Preparing sports guide...')
            show_sports_guide(progress_cb=sports_progress_cb)
            progress.update(100, 'Sports guide loaded successfully!')
        finally:
            progress.close()
        return True

    if control_id == 104:  # Button 4 - Search
        try:
            channels = parse_m3u8(m3u8_path)
            programs = parse_xmltv(xmltv_path)
            addon_path = addon.getAddonInfo('path')
            search_window = SearchWindow('search_window.xml', addon_path, channels=channels, programs=programs)
            search_window.doModal()
            del search_window
        except Exception as e:
            xbmcgui.Dialog().ok("Search Error", f"Error during search: {str(e)}")
        return True

    if control_id == 105:  # Button 5 - Favorites
        try:
            from epggrid import EPGGrid

            progress = xbmcgui.DialogProgress()
            progress.create('Loading Favorites Guide', 'Starting...')
            progress.update(0)

            def progress_cb(percent, message):
                try:
                    progress.update(max(0, min(100, int(percent))), message)
                except Exception:
                    pass

            channels = parse_m3u8(m3u8_path, progress_cb=progress_cb)
            programs = parse_xmltv(xmltv_path, progress_cb=progress_cb)

            progress.update(93, 'Filtering favorites...')
            favorite_channels = [c for c in channels if favorites_manager.is_favorite(c['tvg_id'])]
            if not favorite_channels:
                progress.close()
                xbmcgui.Dialog().ok("TV Guide", "No favorite channels added yet")
                return True

            favorite_channel_ids = [c['tvg_id'] for c in favorite_channels]
            favorite_programs = [p for p in programs if p['channel'] in favorite_channel_ids]
            progress.update(98, 'Opening favorites guide...')
            addon_path = addon.getAddonInfo('path')
            epg_window = EPGGrid(
                'tuepg.guide.experimental.xml',
                addon_path,
                channels=favorite_channels,
                programs=favorite_programs,
                is_favorites_view=True,
            )
            progress.update(100)
            progress.close()
            epg_window.doModal()
            del epg_window
        except Exception as e:
            try:
                progress.close()
            except Exception:
                pass
            xbmcgui.Dialog().ok("Favorites Error", f"Error showing favorites: {str(e)}")
        return True

    if control_id == 106:  # Button 6 - Sports Grid
        try:
            sports = [
                ("MLB", "mlb"),
                ("NBA", "nba"),
                ("NCAAB", "ncaab"),
                ("WNBA", "wnba"),
                ("NHL", "nhl"),
                ("NFL", "nfl"),
                ("MLS", "mls"),
                ("Premier League", "premierleague"),
                ("La Liga", "laliga"),
                ("Bundesliga", "bundesliga"),
                ("Serie A", "seriea"),
                ("Ligue 1", "ligue1"),
                ("Champions League", "championsleague"),
            ]
            dialog = xbmcgui.Dialog()
            choice = dialog.select('[COLOR gold]Select Sport Grid View[/COLOR]', [f"[COLOR orange]{name}[/COLOR]" for name, _ in sports])
            if choice >= 0:
                sport_code = sports[choice][1]
                sport_name = sports[choice][0]
                progress = xbmcgui.DialogProgress()
                progress.create(f'Loading {sport_name} Stats', f'Loading {sport_name} statistics...')
                progress.update(0)
                try:
                    progress.update(25, f'Fetching {sport_name} team data...')
                    progress.update(50, f'Loading {sport_name} game schedules...')
                    progress.update(75, f'Preparing {sport_name} interface...')
                    show_sports_grid(sport_code)
                    progress.update(100, f'{sport_name} stats loaded successfully!')
                finally:
                    progress.close()
        except Exception as e:
            xbmcgui.Dialog().ok("Sports Error", f"Error showing sports grid: {str(e)}")
        return True

    if control_id == 108:  # Button 8 - Show Main Menu
        plugin_url = f"plugin://{addon.getAddonInfo('id')}/?action=show_main"
        xbmc.executebuiltin('Dialog.Close(all)')
        xbmc.sleep(20)
        self.close()
        xbmc.executebuiltin(f'Container.Update({plugin_url})')
        return True

    return False
