import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hello_wallpaper/common/components/dialog/remind_dialog.dart';
import 'package:hello_wallpaper/common/components/view_state_widget.dart';
import 'package:hello_wallpaper/common/storage/favorite_data.dart';
import 'package:hello_wallpaper/models/wallpaper_model.dart';
import 'package:hello_wallpaper/modules/home/home_controller.dart';
import 'package:hello_wallpaper/routes/app_pages.dart';

class FavoriteController extends GetxController {
  static FavoriteController get to => Get.find<FavoriteController>();
  late ScrollController scrollController;
  late ViewState viewState;
  late List<WallpaperData> favoriteList;
  var todayHottestList = <WallpaperData>[];
  WallpaperModel? todayHottestData;

  @override
  void onInit() {
    super.onInit();
    scrollController = ScrollController();
    getData();
    getTodayHottestList();
  }

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

  void getData() {
    favoriteList = FavoriteData().getWallpaperData().reversed.toList();
    _refreshList();
  }

  void _refreshList() {
    viewState = favoriteList.isNotEmpty ? ViewState.normal : ViewState.empty;
    refresh();
  }

  /// 获取今日最热门壁纸
  void getTodayHottestList() {
    // 从分类中随机取3张壁纸
    todayHottestData = HomeController.to.getRandomCls();
    if (todayHottestData != null && todayHottestData!.data != null && todayHottestData!.data!.length >= 3) {
      var flatList = todayHottestData!.data!.map((e) => e).toList();
      todayHottestList = (flatList..shuffle()).take(3).toList();
    }
  }

  /// 点击壁纸
  void onTapItem(int index, bool isFavorite) {
    Get.toNamed(AppPages.wallpaperDet, arguments: {
      'position': index,
      'wallpaperList': isFavorite ? favoriteList : todayHottestList,
    });
  }

  /// 长按壁纸
  void onLongPress(int index) {
    Get.dialog(
      barrierDismissible: false,
      RemindDialog(
        content: 'Are you sure you want to delete the wallpaper?',
        confirmOnTap: () {
          // 计算原始列表中的对应索引
          int indexToRemoveFromDb = FavoriteData().getWallpaperData().length - 1 - index;
          FavoriteData().delete(indexToRemoveFromDb);
          favoriteList.removeAt(index);
          _refreshList();
        },
      ),
    );
  }

  /// 删除所有壁纸
  void deleteAll() {
    Get.dialog(
      barrierDismissible: false,
      RemindDialog(
        content: 'Are you sure to delete all wallpapers?',
        confirmOnTap: () async {
          FavoriteData().clear();
          favoriteList.clear();
          _refreshList();
        },
      ),
    );
  }

  /// 进入分类详情页面
  void onTapViewMore() {
    Get.toNamed(AppPages.clsDet, arguments: todayHottestData);
  }
}
