import 'dart:io';

import 'package:flip_card/flip_card_controller.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:wallpaperx/common/components/easy_loading.dart';
import 'package:wallpaperx/common/storage/favorite_data.dart';
import 'package:wallpaperx/common/storage/history_data.dart';
import 'package:wallpaperx/common/utils/download_util.dart';
import 'package:wallpaperx/common/utils/log_print.dart';
import 'package:wallpaperx/common/utils/permission_util.dart';
import 'package:wallpaperx/config/applovin.dart';
import 'package:wallpaperx/entity/generate_info_model.dart';
import 'package:wallpaperx/entity/image_model.dart';
import 'package:wallpaperx/page/browse_history/browse_history_controller.dart';
import 'package:wallpaperx/page/collection/collection_controller.dart';
import 'package:wallpaperx/routes/app_pages.dart';

class WallpaperDetailV2Controller extends GetxController {
  RxList wallpaperList = [].obs;
  var position = 0;
  var isSetHistory = true;
  var filePath = '';
  late final PageController pageController;
  late final FlipCardController flipCardController;
  RxBool isFavorite = false.obs;
  RxBool showImgInfo = false.obs;

  @override
  void onInit() {
    super.onInit();
    Map<String, dynamic> arguments = Get.arguments ?? {};
    position = arguments['position'] ?? 0;
    isSetHistory = arguments['isSetHistory'] ?? true;
    wallpaperList = arguments['wallpaperList'] ?? <ImageModel>[];
    pageController = PageController(initialPage: position);
    flipCardController = FlipCardController();
    LogPrint.d(wallpaperList[position].imageUrl);
    int index = FavoriteData().getWallpaperData().indexWhere(
        (element) => element.imageUrl == wallpaperList[position].imageUrl);
    if (index != -1) {
      isFavorite.value = true;
    }
  }

  @override
  void onClose() {
    ApplovinUtil().showAdIfReady();
    pageController.dispose();
    super.onClose();
  }

  @override
  void onReady() {
    super.onReady();
    if (isSetHistory) {
      addHistory(position);
    }
  }

  /// 图片切换
  void onPageChanged(int position, {int? showTitle}) {
    this.position = position;
    filePath = '';
    if (isSetHistory) {
      addHistory(position);
    }
    update(["buildImageInfo"]);
    int indexOf = FavoriteData().getWallpaperData().indexWhere(
        (element) => element.imageUrl == wallpaperList[position].imageUrl);
    if (indexOf != -1) {
      isFavorite.value = true;
    } else {
      isFavorite.value = false;
    }
  }

  /// 下载
  void downloadImg({File? file}) {
    if (Get.isSnackbarOpen) {
      return;
    }
    DownloadUtil.downloadFile('${wallpaperList[position].imageUrl}',
        (savePath) async {
      filePath = savePath;
      bool canSave = true;
      if (Platform.isIOS) {
        canSave = await PermissionUtil.checkPermission(
          [Permission.photosAddOnly],
        );
      }
      if (canSave) {
        final result =
            await ImageGallerySaver.saveImage(File(filePath).readAsBytesSync());
        if (result['isSuccess']) {
          toast('Saved to album');
        } else {
          toast('Unable to save to album');
        }
      }
    });
  }

  /// 收藏
  void collectionImage({ImageModel? imageModel}) {
    ImageModel imageModel = wallpaperList[position];
    // 未收藏过的才保存
    int index = FavoriteData()
        .getWallpaperData()
        .indexWhere((element) => element.imageUrl == imageModel.imageUrl);
    LogPrint.d(index);
    if (index == -1) {
      FavoriteData().setWallpaperData(imageModel);
      isFavorite.value = true;
    } else {
      FavoriteData().delete(index);
      isFavorite.value = false;
    }
    // 刷新收藏列表
    if (Get.isRegistered<CollectionController>()) {
      CollectionController.to.getFavoriteList();
      if (wallpaperList.isEmpty) {
        Get.back();
      } else {
        int indexOf = FavoriteData().getWallpaperData().indexWhere(
            (element) => element.imageUrl == wallpaperList[position].imageUrl);
        if (indexOf != -1) {
          isFavorite.value = true;
        } else {
          isFavorite.value = false;
        }
      }
    }
  }

  /// 浏览记录
  void addHistory(index, {ImageModel? imageModel}) {
    ImageModel imageModel = wallpaperList[index];
    int indexOf = HistoryData().getWallpaperData().indexWhere(
          (element) => element.imageUrl == wallpaperList[index].imageUrl,
        );
    if (indexOf != -1) HistoryData().delete(indexOf);
    HistoryData().setWallpaperData(imageModel);
    // 刷新浏览列表
    if (Get.isRegistered<BrowseHistoryController>()) {
      BrowseHistoryController.to.getHistoryList();
    }
  }

  /// 跳转分类明细
  void toCategoryItem(title, {String? categoryInfo}) {
    Get.toNamed(AppPages.categoryItem, arguments: title);
  }

  /// 复制
  void copyPrompt(GenerateInfoModel? generateInfo) {
    Map textMap = {
      "Prompt": generateInfo!.prompt,
      "Negative Prompt": generateInfo.negativePrompt,
    };
    Clipboard.setData(ClipboardData(text: textMap.toString()));
    toast("Copied");
  }

  /// 翻转并且播放广告
  void flipCardAndShowAd() {
    ApplovinUtil().showAdIfReady().then((e) {
      flipCardController.toggleCard();
    });
  }

  /// 翻转
  void flipCard() {
    flipCardController.toggleCard();
  }

}
