import xbmc
import xbmcgui
import xbmcaddon

from wcs import utils
from wcs.metadata import TMDbClient as tmdb_handler
from wcs.ui import UI as ui
from wcs.utils import search_and_play_movie


class CollectionDialog(xbmcgui.WindowXMLDialog):
    def __init__(self, xmlFilename, addonPath, skin="Default", theme="Default", collection_id=None):
        super(CollectionDialog, self).__init__()
        self.collection_id = collection_id
        self.addon = xbmcaddon.Addon()

    def onInit(self):
        if not self.collection_id:
            ui.popinfo("Chyba: ID kolekce nebylo předáno do dialogu.", self.addon.getAddonInfo('name'), icon=xbmcgui.NOTIFICATION_ERROR)
            self.close()
            return

        collection_details = tmdb_handler.get_collection_details(self.collection_id)
        if not collection_details:
            ui.popinfo(f"Nepodařilo se načíst detaily pro kolekci ID: {self.collection_id}", self.addon.getAddonInfo('name'), icon=xbmcgui.NOTIFICATION_WARNING)
            self.close()
            return

        collection_name_from_tmdb = collection_details.get('name', 'Neznámá kolekce')
        if collection_name_from_tmdb.endswith(" (kolekce)"):
            collection_name_base = collection_name_from_tmdb[:-11].strip()
        elif collection_name_from_tmdb.endswith(" Collection"):
            collection_name_base = collection_name_from_tmdb[:-11].strip()
        else:
            collection_name_base = collection_name_from_tmdb

        poster_path = collection_details.get('poster_path')
        if poster_path:
            collection_poster_url = f"https://image.tmdb.org/t/p/w342{poster_path}"
            self.setProperty('WCS.Collection.Poster', collection_poster_url)
        else:
            self.setProperty('WCS.Collection.Poster', '')

        self.setProperty('WCS.Collection.Plot', collection_details.get('overview', 'Popis není k dispozici.'))

        list_items = []
        panel = self.getControl(5000)
        if not panel:
            xbmc.log(f"{self.addon.getAddonInfo('id')}: Panel s ID 5000 nebyl nalezen v DialogCollectionDetails.xml", xbmc.LOGERROR)
            self.close()
            return
        panel.reset()

        parts = collection_details.get('parts', [])
        if not parts:
            self.setProperty('WCS.Collection.Name', collection_name_base)
            ui.popinfo(f"Kolekce '{collection_name_base}' neobsahuje žádné filmy.", self.addon.getAddonInfo('name'), icon=xbmcgui.NOTIFICATION_INFO)
            return

        def get_release_year_for_sort(part_data):
            release_date_str = part_data.get('release_date', '')
            if release_date_str and isinstance(release_date_str, str) and len(release_date_str) >= 4:
                try:
                    return int(release_date_str[:4])
                except ValueError:
                    return float('inf')
            return float('inf')

        parts.sort(key=get_release_year_for_sort)

        for film_in_collection in parts:
            if not film_in_collection.get('id') or not film_in_collection.get('title'):
                continue

            li_label = film_in_collection['title']
            li = xbmcgui.ListItem(li_label)

            full_movie_details = tmdb_handler.get_movie_detailed_info(film_in_collection['id'])
            current_film_data = full_movie_details if full_movie_details else film_in_collection

            item_poster_path = current_film_data.get('poster_path')
            item_thumb_url = f"https://image.tmdb.org/t/p/w92{item_poster_path}" if item_poster_path else ""
            item_poster_url = f"https://image.tmdb.org/t/p/w500{item_poster_path}" if item_poster_path else ""

            art_data = {'thumb': item_thumb_url, 'icon': item_thumb_url, 'poster': item_poster_url}
            art_data = {k: v for k, v in art_data.items() if v}
            if art_data:
                li.setArt(art_data)

            year_str = str(current_film_data.get('release_date', ''))[:4] if current_film_data.get('release_date') else ''
            plot = current_film_data.get('overview', '')
            vote_average = current_film_data.get('vote_average')
            rating_str = f"{vote_average:.1f}" if isinstance(vote_average, (float, int)) and vote_average > 0 else ""
            director = current_film_data.get('director', '')
            writer = current_film_data.get('writer', '')

            info_video = {
                'plot': plot, 'plotoutline': plot, 'title': li_label,
                'originaltitle': current_film_data.get('original_title', li_label),
                'year': int(year_str) if year_str else 0,
                'rating': float(vote_average) if isinstance(vote_average, (float, int)) and vote_average > 0 else 0.0,
                'director': director, 'writer': writer,
            }
            utils.set_video_info_tag(li, info_video)

            li.setProperty('year', year_str)
            li.setProperty('tmdb_id', str(film_in_collection['id']))
            if rating_str:
                li.setProperty('rating_text', rating_str)
            list_items.append(li)

        final_collection_name = collection_name_base
        if list_items:
            valid_film_count = len(list_items)
            years = []
            for item in list_items:
                year_prop = item.getProperty('year')
                if year_prop:
                    try:
                        years.append(int(year_prop))
                    except ValueError:
                        pass

            min_valid_year = min(years) if years else None
            max_valid_year = max(years) if years else None

            year_range_str = ""
            if min_valid_year is not None and max_valid_year is not None:
                year_range_str = str(min_valid_year) if min_valid_year == max_valid_year else f"{min_valid_year}-{max_valid_year}"

            film_count_label = "filmů"
            if valid_film_count == 1:
                film_count_label = "film"
            elif 2 <= valid_film_count <= 4:
                film_count_label = "filmy"
            film_count_str = f"{valid_film_count} {film_count_label}"

            info_parts = []
            if year_range_str:
                info_parts.append(year_range_str)
            info_parts.append(film_count_str)
            final_collection_name = f"{collection_name_base} ({', '.join(info_parts)})"

        self.setProperty('WCS.Collection.Name', final_collection_name)

        if list_items:
            panel.addItems(list_items)
            self.setFocus(panel)
            try:
                panel.selectItem(0)
                xbmc.log(f"[WCS - CollectionDialog] Explicitly selected item 0 in panel 5000.", xbmc.LOGINFO)
            except Exception as e:
                xbmc.log(f"[WCS - CollectionDialog] Error selecting item 0: {e}", xbmc.LOGERROR)
        else:
            xbmc.log(f"[WCS - CollectionDialog] No items to add to panel after processing parts.", xbmc.LOGINFO)

    def onClick(self, controlID):
        xbmc.log(f"[WCS - CollectionDialog] onClick triggered with controlID: {controlID}", xbmc.LOGINFO)
        if controlID == 5010 or controlID == 5000:
            panel_ctrl = self.getControl(5000)
            if not panel_ctrl:
                xbmc.log(f"[WCS - CollectionDialog] Panel control 5000 not found in onClick!", xbmc.LOGERROR)
                return
            selected_item = panel_ctrl.getSelectedItem()
            if selected_item:
                tmdb_id = selected_item.getProperty('tmdb_id')
                item_label = selected_item.getLabel()
                xbmc.log(f"[WCS - CollectionDialog] Selected item: {item_label}, tmdb_id: {tmdb_id}", xbmc.LOGINFO)
                if tmdb_id:
                    dialog = xbmcgui.Dialog()
                    options = [
                        "Přidat do Moje filmy",
                        "Přidat do knihovny Kodi",
                        "Zobrazit detaily",
                        "Přehrát",
                        "Zrušit"
                    ]
                    dialog_title = f"Akce: {item_label}"
                    choice = dialog.select(dialog_title, 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 ''
                        search_and_play_movie(title, year, plot, poster, fanart, rating, genre, director, runtime, self.addon)
                    return
        elif controlID == 5001:
            pass
        else:
            xbmc.log(f"[WCS - CollectionDialog] Click on unhandled controlID: {controlID}", xbmc.LOGINFO)

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


