import xbmc
import xbmcgui
import xbmcaddon
from urllib.parse import quote_plus

from wcs.metadata import TMDbClient as tmdb_handler
from wcs import utils


class ActorDialog(xbmcgui.WindowXMLDialog):
    def __init__(self, xmlFilename, addonPath, skin="Default", theme="Default", actor_id=None, media_type='movie', person_type='actor'):
        super(ActorDialog, self).__init__(xmlFilename, addonPath, skin, theme)
        self.actor_id = actor_id
        self.media_type = media_type or 'movie'
        self.person_type = person_type or 'actor'
        self.addon = xbmcaddon.Addon()

    def onInit(self):
        if not self.actor_id:
            from wcs.ui import UI as ui
            ui.popinfo("Chyba: ID herce nebylo předáno do dialogu.", self.addon.getAddonInfo('name'), icon=xbmcgui.NOTIFICATION_ERROR)
            self.close()
            return

        actor_data = tmdb_handler.get_actor_details(self.actor_id)
        if not actor_data:
            from wcs.ui import UI as ui
            ui.popinfo(f"Nepodařilo se načíst detaily pro herce ID: {self.actor_id}", self.addon.getAddonInfo('name'), icon=xbmcgui.NOTIFICATION_WARNING)
            self.close()
            return

        self.setProperty('WCS.Actor.Name', actor_data.get('name', ''))
        profile_path = actor_data.get('profile_path')
        if profile_path:
            self.setProperty('WCS.Actor.Profile', f"https://image.tmdb.org/t/p/w342{profile_path}")
        else:
            self.setProperty('WCS.Actor.Profile', '')
        self.setProperty('WCS.Actor.Bio', actor_data.get('biography', ''))
        self.setProperty('WCS.Actor.Department', actor_data.get('known_for_department', ''))
        self.setProperty('WCS.Actor.Birthday', actor_data.get('birthday', ''))
        self.setProperty('WCS.Actor.PlaceOfBirth', actor_data.get('place_of_birth', ''))

        person_text = "hercem"
        if self.person_type == 'creator':
            person_text = "tvůrcem"
        elif self.person_type == 'director':
            person_text = "režisérem"

        if self.media_type == 'tv':
            title_label = f"Seriály s {person_text}: {actor_data.get('name', '')}"
        else:
            title_label = f"Filmy s {person_text}: {actor_data.get('name', '')}"
        self.setProperty('WCS.Actor.Title', title_label)

        if self.media_type == 'tv':
            if self.person_type == 'creator':
                items = tmdb_handler.get_creator_tv(self.actor_id)
            else:
                items = tmdb_handler.get_actor_tv(self.actor_id)
        else:
            if self.person_type == 'creator':
                items = tmdb_handler.get_creator_movies(self.actor_id)
            else:
                items = tmdb_handler.get_actor_movies(self.actor_id)

        panel = self.getControl(5000)
        if not panel:
            xbmc.log(f"[WCS - ActorDialog] Panel s ID 5000 nebyl nalezen.", xbmc.LOGERROR)
            self.close()
            return
        panel.reset()

        favorite_text = "Přidat herce do oblíbených"
        game_text = "Hrát hru s hercem"
        if self.person_type == 'creator':
            favorite_text = "Přidat tvůrce do oblíbených"
            game_text = "Hrát hru s tvůrcem"
        elif self.person_type == 'director':
            favorite_text = "Přidat režiséra do oblíbených"
            game_text = "Hrát hru s režisérem"

        actor_item = xbmcgui.ListItem(label=favorite_text)
        actor_item.setArt({'thumb': self.getProperty('WCS.Actor.Profile') or 'DefaultActor.png', 'poster': self.getProperty('WCS.Actor.Profile') or 'DefaultActor.png'})
        actor_item.setProperty('is_add_favorite', '1')
        actor_item.setProperty('actor_name', actor_data.get('name', ''))
        actor_item.setProperty('actor_department', actor_data.get('known_for_department', ''))
        actor_item.setProperty('tmdb_id', str(self.actor_id))
        actor_item.setProperty('plot', actor_data.get('biography', ''))
        panel.addItem(actor_item)

        game_item = xbmcgui.ListItem(label=game_text)
        game_item.setArt({'thumb': self.getProperty('WCS.Actor.Profile') or 'DefaultActor.png'})
        game_item.setProperty('is_start_actor_game', '1')
        game_item.setProperty('tmdb_id', str(self.actor_id))
        panel.addItem(game_item)

        for item_data in items:
            if self.media_type == 'tv':
                label = item_data.get('name', '')
                year_str = str(item_data.get('first_air_date', ''))[:4] if item_data.get('first_air_date') else ''
                poster_path = item_data.get('poster_path')
                poster_url = f"https://image.tmdb.org/t/p/w500{poster_path}" if poster_path else 'DefaultVideo.png'
                thumb_url = f"https://image.tmdb.org/t/p/w185{poster_path}" if poster_path else 'DefaultVideo.png'
                plot = item_data.get('overview', '')
                vote_average = item_data.get('vote_average')
                rating_str = f"{vote_average:.1f}" if isinstance(vote_average, (int, float)) and vote_average > 0 else ''
                info_video = {
                    'title': label,
                    'originaltitle': item_data.get('original_name', label),
                    'year': int(year_str) if year_str.isdigit() else 0,
                    'plot': plot,
                    'rating': float(vote_average) if isinstance(vote_average, (int, float)) and vote_average > 0 else 0.0,
                    'mediatype': 'tvshow'
                }
            else:
                label = item_data.get('title', '')
                year_str = str(item_data.get('release_date', ''))[:4] if item_data.get('release_date') else ''
                poster_path = item_data.get('poster_path')
                poster_url = f"https://image.tmdb.org/t/p/w500{poster_path}" if poster_path else 'DefaultVideo.png'
                thumb_url = f"https://image.tmdb.org/t/p/w185{poster_path}" if poster_path else 'DefaultVideo.png'
                plot = item_data.get('overview', '')
                vote_average = item_data.get('vote_average')
                rating_str = f"{vote_average:.1f}" if isinstance(vote_average, (int, float)) and vote_average > 0 else ''
                genre = ', '.join([g['name'] for g in item_data.get('genres', [])]) if item_data.get('genres') else ''
                director = item_data.get('director', '') if item_data.get('director') else ''
                info_video = {
                    'title': label,
                    'originaltitle': item_data.get('original_title', label),
                    'year': int(year_str) if year_str.isdigit() else 0,
                    'plot': plot,
                    'rating': float(vote_average) if isinstance(vote_average, (int, float)) and vote_average > 0 else 0.0,
                    'genre': genre,
                    'director': director,
                }
            listitem = xbmcgui.ListItem(label=label)
            listitem.setProperty('tmdb_id', str(item_data.get('id', '')))
            listitem.setProperty('year', year_str)
            listitem.setProperty('plot', plot)
            if rating_str:
                listitem.setProperty('rating_text', rating_str)
            listitem.setArt({'thumb': thumb_url, 'poster': poster_url})
            listitem.setProperty('is_add_favorite', '0')
            utils.set_video_info_tag(listitem, info_video)
            panel.addItem(listitem)

        self.setFocus(panel)
        try:
            panel.selectItem(0)
        except Exception as e:
            xbmc.log(f"[WCS - ActorDialog] Error selecting item 0: {e}", xbmc.LOGERROR)

    def onClick(self, controlID):
        if controlID == 5010 or controlID == 5000:
            panel_ctrl = self.getControl(5000)
            if not panel_ctrl:
                xbmc.log(f"[WCS - ActorDialog] Panel control 5000 not found in onClick!", xbmc.LOGERROR)
                return
            selected_item = panel_ctrl.getSelectedItem()
            if selected_item:
                if selected_item.getProperty('is_start_actor_game') == '1':
                    from wcs.games.DialogWcsTextGame import TextGameWindow
                    actor_data = tmdb_handler.get_actor_details(self.actor_id)
                    if not actor_data:
                        from wcs.ui import UI as ui
                        error_text = "Nepodařilo se načíst detaily herce."
                        if self.person_type == 'creator':
                            error_text = "Nepodařilo se načíst detaily tvůrce."
                        elif self.person_type == 'director':
                            error_text = "Nepodařilo se načíst detaily režiséra."
                        ui.popinfo(error_text, self.addon.getAddonInfo('name'), icon=xbmcgui.NOTIFICATION_ERROR)
                        return
                    profile_path = actor_data.get('profile_path')
                    fanart_url = f"https://image.tmdb.org/t/p/w780{profile_path}" if profile_path else ''
                    window = TextGameWindow(
                        "games/DialogWcsTextGame.xml",
                        self.addon.getAddonInfo('path'),
                        "Default",
                        title=actor_data.get('name', ''),
                        fanart=fanart_url,
                        plot=actor_data.get('biography', '')[:500],
                        genre='',
                        media_type=self.person_type,
                        actor_data=actor_data,
                        banner_fanart=fanart_url,
                        episode_title="",
                        season_number=None,
                        episode_number=None
                    )
                    window.doModal()
                    del window
                    return
                if selected_item.getProperty('is_add_favorite') == '1':
                    actor_id = self.actor_id
                    actor_data = tmdb_handler.get_actor_details(actor_id)
                    actor_name = actor_data.get('name', '') if actor_data else ''
                    url = f"plugin://{self.addon.getAddonInfo('id')}?action=tmdb_add_actor_to_favorites&actor_id={actor_id}&actor_name={quote_plus(actor_name)}"
                    xbmc.executebuiltin(f"RunPlugin({url})")
                    return
                tmdb_id = selected_item.getProperty('tmdb_id')
                item_label = selected_item.getLabel()
                if tmdb_id:
                    if self.media_type == 'tv':
                        dialog = xbmcgui.Dialog()
                        options = [
                            "Přidat do Moje seriály",
                            "Přidat do knihovny Kodi",
                            "Zobrazit detaily",
                            "Zrušit"
                        ]
                        choice = dialog.select(f"Akce: {item_label}", options)
                        if choice == 0:
                            from wcs.ui.UI import add_series_item_to_list
                            add_series_item_to_list(self.addon, tmdb_id, item_label)
                        elif choice == 1:
                            from wcs.library import LibraryManager as library
                            library.check_settings_and_add_item({'media_type': 'series', 'series_id': tmdb_id}, self.addon)
                        elif choice == 2:
                            detail_url = f"plugin://{self.addon.getAddonInfo('id')}?action=show_wcs_details&media_type=tv&tmdb_id={tmdb_id}"
                            xbmc.executebuiltin(f"RunPlugin({detail_url})")
                            self.close()
                        return
                    else:
                        dialog = xbmcgui.Dialog()
                        options = [
                            "Přidat do Moje filmy",
                            "Přidat do knihovny Kodi",
                            "Zobrazit detaily",
                            "Přehrát",
                            "Zrušit"
                        ]
                        choice = dialog.select(f"Akce: {item_label}", options)
                        if choice == 0:
                            from wcs.ui.UI import add_movie_item_to_list
                            add_movie_item_to_list(self.addon, tmdb_id, item_label)
                        elif choice == 1:
                            from wcs.library import LibraryManager as library
                            library.check_settings_and_add_item({'media_type': 'movie', 'movie_id': tmdb_id}, self.addon)
                        elif choice == 2:
                            detail_url = f"plugin://{self.addon.getAddonInfo('id')}?action=show_wcs_details&media_type=movie&tmdb_id={tmdb_id}"
                            xbmc.executebuiltin(f"RunPlugin({detail_url})")
                            self.close()
                        elif choice == 3:
                            title = item_label or ''
                            year = selected_item.getProperty('year') or ''
                            poster = selected_item.getArt('poster') or ''
                            fanart = ''
                            rating = selected_item.getProperty('rating_text') or ''
                            genre = ''
                            director = ''
                            runtime = ''
                            plot = selected_item.getProperty('plot') or ''
                            from wcs.utils import search_and_play_movie
                            search_and_play_movie(title, year, plot, poster, fanart, rating, genre, director, runtime, self.addon)
                        return

    def onAction(self, action):
        if action.getId() == xbmcgui.ACTION_NAV_BACK or action.getId() == xbmcgui.ACTION_PREVIOUS_MENU:
            self.close()


