import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:tone_snap/components/view_state_widget.dart';
import 'package:tone_snap/data/api/music_api.dart';
import 'package:tone_snap/data/enum/music_type.dart';
import 'package:tone_snap/data/models/music_model.dart';
import 'package:tone_snap/data/models/search_result_model.dart';
import 'package:tone_snap/data/models/search_result_more_model.dart';
import 'package:tone_snap/modules/sideb/search_result/search_result_controller.dart';
import 'package:tone_snap/routes/app_routes.dart';
import 'package:tone_snap/utils/obj_util.dart';

class SearchResultChildController extends GetxController {
  var viewState = ViewState.loading.obs;
  var scrollController = ScrollController();
  var musicList = <Rx<MusicModel>>[].obs;
  String? params;
  String? continuation;
  String? clickTrackingParams;
  var refreshController = EasyRefreshController(
    controlFinishLoad: true,
  );

  @override
  void onReady() {
    super.onReady();
    _searchResult();
  }

  @override
  void onClose() {
    refreshController.dispose();
    scrollController.dispose();
    super.onClose();
  }

  void setParams(String? params) {
    this.params = params;
  }

  void onLoad() {
    _searchResultLoadMore();
  }

  Future<void> _searchResult() async {
    Map<String, dynamic> queryParameters = {
      'prettyPrint': false,
      'query': SearchResultController.to.searchKeyword,
      'params': params
    };
    SearchResultModel? searchResultModel = await MusicApi.search<SearchResultModel>(queryParameters: queryParameters, formJson: SearchResultModel.fromMap);
    final list = <MusicModel>[];
    if (searchResultModel != null) {
      var tabs = searchResultModel.contents?.tabbedSearchResultsRenderer?.tabs;
      if (tabs != null && tabs.isNotEmpty) {
        var contents1 = tabs[0].tabRenderer?.content?.sectionListRenderer?.contents;
        if (contents1 != null && contents1.isNotEmpty) {
          var continuations = contents1[0].musicShelfRenderer?.continuations;
          if (continuations != null && continuations.isNotEmpty) {
            continuation = continuations[0].nextContinuationData?.continuation;
            clickTrackingParams = continuations[0].nextContinuationData?.clickTrackingParams;
          }
          for (var o in contents1) {
            if (o.musicShelfRenderer != null) {
              var contents2 = o.musicShelfRenderer?.contents;
              if (contents2 != null && contents2.isNotEmpty) {
                for (var e in contents2) {
                  var musicModel = MusicModel();
                  var thumbnails = e.musicResponsiveListItemRenderer?.thumbnail?.musicThumbnailRenderer?.thumbnail?.thumbnails;
                  if (thumbnails != null && thumbnails.isNotEmpty) {
                    musicModel.coverUrl = thumbnails.last.url;
                  }
                  var flexColumns = e.musicResponsiveListItemRenderer?.flexColumns;
                  if (flexColumns != null && flexColumns.isNotEmpty) {
                    for (var i = 0; i < flexColumns.length; ++i) {
                      var m = flexColumns[i];
                      var runs = m.musicResponsiveListItemFlexColumnRenderer?.text?.runs;
                      if (runs != null && runs.isNotEmpty) {
                        if (i == 0) {
                          musicModel.title = runs[0].text;
                          musicModel.videoId = runs[0].navigationEndpoint?.watchEndpoint?.videoId;
                          musicModel.musicType = runs[0].navigationEndpoint?.watchEndpoint?.watchEndpointMusicSupportedConfigs?.watchEndpointMusicConfig?.musicVideoType;
                        } else {
                          musicModel.subtitle = ObjUtil.getStr(musicModel.subtitle) + runs.map((e) => e.text).join();
                        }
                      }
                    }
                  }
                  var items = e.musicResponsiveListItemRenderer?.menu?.menuRenderer?.items;
                  if (items != null && items.isNotEmpty) {
                    musicModel.playlistId = items[0].menuNavigationItemRenderer?.navigationEndpoint?.watchEndpoint?.playlistId;
                  }
                  if (e.musicResponsiveListItemRenderer?.navigationEndpoint != null) {
                    musicModel.browseId = e.musicResponsiveListItemRenderer?.navigationEndpoint?.browseEndpoint?.browseId;
                    musicModel.musicType = e.musicResponsiveListItemRenderer?.navigationEndpoint?.browseEndpoint?.browseEndpointContextSupportedConfigs?.browseEndpointContextMusicConfig?.pageType;
                  }
                  if (musicModel.musicType == MusicType.musicVideoTypeAtv.name
                      || musicModel.musicType == MusicType.musicPageTypeAlbum.name
                      || musicModel.musicType == MusicType.musicPageTypePlaylist.name) {
                    list.add(musicModel);
                  }
                }
              }
            }
          }
        }
      }
    }
    musicList.value = list.map((e) => e.obs).toList();
    viewState.value = musicList.isNotEmpty ? ViewState.normal : ViewState.empty;
  }

  Future<void> _searchResultLoadMore() async {
    if (ObjUtil.isEmpty(continuation)) {
      return;
    }
    Map<String, dynamic> queryParameters = {
      'ctoken': continuation,
      'continuation': continuation,
      'type': 'next',
      'itct': clickTrackingParams,
      'prettyPrint': false
    };
    refreshController.callLoad();
    SearchResultMoreModel? searchResultMoreModel = await MusicApi.search<SearchResultMoreModel>(queryParameters: queryParameters, formJson: SearchResultMoreModel.fromMap);
    final list = <MusicModel>[];
    if (searchResultMoreModel != null) {
      var continuations = searchResultMoreModel.continuationContents?.musicShelfContinuation?.continuations;
      if (continuations != null && continuations.isNotEmpty) {
        continuation = continuations[0].nextContinuationData?.continuation;
        clickTrackingParams = continuations[0].nextContinuationData?.clickTrackingParams;
      } else {
        continuation = null;
        clickTrackingParams = null;
      }
      var contents = searchResultMoreModel.continuationContents?.musicShelfContinuation?.contents;
      if (contents != null && contents.isNotEmpty) {
        for (var o in contents) {
          var musicModel = MusicModel();
          var thumbnails = o.musicResponsiveListItemRenderer?.thumbnail?.musicThumbnailRenderer?.thumbnail?.thumbnails;
          if (thumbnails != null && thumbnails.isNotEmpty) {
            musicModel.coverUrl = thumbnails.last.url;
          }
          var flexColumns = o.musicResponsiveListItemRenderer?.flexColumns;
          if (flexColumns != null && flexColumns.isNotEmpty) {
            for (var i = 0; i < flexColumns.length; ++i) {
              var m = flexColumns[i];
              var runs = m.musicResponsiveListItemFlexColumnRenderer?.text?.runs;
              if (runs != null && runs.isNotEmpty) {
                if (i == 0) {
                  musicModel.title = runs[0].text;
                  musicModel.videoId = runs[0].navigationEndpoint?.watchEndpoint?.videoId;
                  musicModel.musicType = runs[0].navigationEndpoint?.watchEndpoint?.watchEndpointMusicSupportedConfigs?.watchEndpointMusicConfig?.musicVideoType;
                } else {
                  musicModel.subtitle = ObjUtil.getStr(musicModel.subtitle) + runs.map((e) => e.text).join();
                }
              }
            }
          }
          var items = o.musicResponsiveListItemRenderer?.menu?.menuRenderer?.items;
          if (items != null && items.isNotEmpty) {
            musicModel.playlistId = items[0].menuNavigationItemRenderer?.navigationEndpoint?.watchEndpoint?.playlistId;
          }
          if (o.musicResponsiveListItemRenderer?.navigationEndpoint != null) {
            musicModel.browseId = o.musicResponsiveListItemRenderer?.navigationEndpoint?.browseEndpoint?.browseId;
            musicModel.musicType = o.musicResponsiveListItemRenderer?.navigationEndpoint?.browseEndpoint?.browseEndpointContextSupportedConfigs?.browseEndpointContextMusicConfig?.pageType;
          }
          list.add(musicModel);
        }
      }
    }
    musicList.addAll(list.map((e) => e.obs).toList());
    if (searchResultMoreModel != null) {
      if (ObjUtil.isNotEmpty(continuation)) {
        refreshController.finishLoad(IndicatorResult.success);
      } else {
        refreshController.finishLoad(IndicatorResult.noMore);
      }
    } else {
      refreshController.finishLoad(IndicatorResult.fail);
    }
    viewState.value = musicList.isNotEmpty ? ViewState.normal : ViewState.empty;
  }

  void onTapItem(MusicModel musicModel) {
    if (musicModel.musicType == MusicType.musicVideoTypeAtv.name) {
      Get.toNamed(AppRoutes.playPage, arguments: {
        'videoId': musicModel.videoId,
        'playlistId': musicModel.playlistId,
      });
    } else if (musicModel.musicType == MusicType.musicPageTypeAlbum.name
        || musicModel.musicType == MusicType.musicPageTypePlaylist.name) {
      Get.toNamed(AppRoutes.albumSongList, arguments: {
        'browseId': musicModel.browseId,
        'params': musicModel.params,
        'coverUrl': musicModel.coverUrl,
        'title': musicModel.title,
        'subtitle': musicModel.subtitle,
      });
    }
  }
}
