import 'package:clean/base/base_controller.dart';
import 'package:clean/data/bean/photos_type.dart';
import 'package:clean/module/image_picker/image_picker_util.dart';
import 'package:clean/module/people_photo/photo_group.dart';
import 'package:clean/module/photo_preview/photo_preview_view.dart';
import 'package:clean/utils/toast_util.dart';
import 'package:get/get.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

class ScreenShotsController extends BaseController {
  late String titleName;
  final RxList<PhotoGroup> photoGroups = <PhotoGroup>[].obs;
  final RxDouble selectedFilesSize = 0.0.obs;
  RxInt selectedFileCount = 0.obs;
  final RxSet<String> selectedPhotosIds = <String>{}.obs;

  Future<void> updateSelectedFilesSize() async {
    double totalSize = 0;
    for (var group in photoGroups) {
      for (int i = 0; i < group.images.length; i++) {
        if (group.selectedImages[i]) {
          final file = await group.images[i].file;
          if (file != null) {
            totalSize += file.lengthSync();
          }
        }
      }
    }
    selectedFilesSize.value = totalSize / 1024; // Convert to KB
  }


  void toggleImageSelection(List<AssetEntity> images, int imageIndex) {
    final group = getGroupByImages(images);
    final image = group.images[imageIndex];
    final selected = !group.selectedImages[imageIndex];

    group.selectedImages[imageIndex] = selected;
    _updateSelectedScreenshotsPhotosIds(image.id, selected);

    group.isSelected.value = group.selectedImages.every((selected) => selected);

    updateSelectedFilesSize();
    selectedFileCount.value = selectedPhotosIds.length;
  }

  void clickImage(List<AssetEntity> images, int imageIndex) {
    final group = getGroupByImages(images);
    final image = group.images[imageIndex];


    if (titleName == "Screenshots") {
      ImagePickerUtil.selectedScreenshotPhotosIds.assignAll(selectedPhotosIds);
      PhotoPreviewPage.start(PhotosType.screenshots, image.id);
    } else if (titleName == "Blurry") {
      ImagePickerUtil.selectedBlurryPhotosIds.assignAll(selectedPhotosIds);
      PhotoPreviewPage.start(PhotosType.blurryPhotos, image.id);
    }

  }


  void toggleGroupSelection(List<AssetEntity> images) {
    final group = getGroupByImages(images);
    final newValue = !group.isSelected.value;
    group.toggleSelectAll(newValue);

    for (var image in group.images) {
      _updateSelectedScreenshotsPhotosIds(image.id, newValue);
    }

    updateSelectedFilesSize();
    selectedFileCount.value = selectedPhotosIds.length;
  }
  //
  // // 通过标题获取照片组
  // PhotoGroup _getGroupByTitle(String groupTitle) {
  //   return photoGroups.firstWhere((g) => g.title == groupTitle);
  // }

  // // 通过photoGroup的images来获取图片组

  PhotoGroup getGroupByImages(List<AssetEntity> images) {
    final imageIds = images.map((img) => img.id).toSet();
    return photoGroups.firstWhere((group) =>
        group.images.every((image) => imageIds.contains(image.id))
    );
  }
  void _updateSelectedScreenshotsPhotosIds(String photoId, bool isSelected) {
    if (isSelected) {
      selectedPhotosIds.add(photoId);
    } else {
      selectedPhotosIds.remove(photoId);
    }
  }

  void restoreSelections() {
    if (titleName == "Screenshots") {
      selectedPhotosIds.assignAll(ImagePickerUtil.selectedScreenshotPhotosIds);

    } else if (titleName == "Blurry") {
      selectedPhotosIds.assignAll(ImagePickerUtil.selectedBlurryPhotosIds);
    }

    for (var group in photoGroups) {
      for (int i = 0; i < group.images.length; i++) {
        if (selectedPhotosIds.contains(group.images[i].id)) {
          group.selectedImages[i] = true;
        }else {
          group.selectedImages[i] = false;
        }
      }
      group.isSelected.value =
          group.selectedImages.every((selected) => selected);
    }
    updateSelectedFilesSize();
    selectedFileCount.value = selectedPhotosIds.length;
  }

  @override
  void onInit() async {
    // TODO: implement onInit
    super.onInit();
    _getArgs();
    loadScreenshots();
    restoreSelections();
  }

  void _getArgs() {
    titleName = parameters?['titleName'];
  }

  void loadScreenshots() {
    // 清空现有数据
    photoGroups.clear();

    // 将 ImagePickerUtil 中的相似照片转换为 PhotoGroup

    if (titleName == "Screenshots") {
      final photoGroup = ImagePickerUtil.screenshotPhotos;
      if (photoGroup.isNotEmpty) {
        photoGroups.add(PhotoGroup(
          isSelected: false,
          images: photoGroup,
        ));
      }
      selectedPhotosIds.assignAll(ImagePickerUtil.selectedScreenshotPhotosIds);
    } else if (titleName == "Blurry") {

      final photoGroup = ImagePickerUtil.blurryPhotos;
      if (photoGroup.isNotEmpty) {
        photoGroups.add(PhotoGroup(
          isSelected: false,
          images: photoGroup,
        ));
      }
      selectedPhotosIds.assignAll(ImagePickerUtil.selectedBlurryPhotosIds);
    }
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
    if (titleName == "Screenshots") {
      ImagePickerUtil.selectedScreenshotPhotosIds.assignAll(selectedPhotosIds);
    } else if (titleName == "Blurry") {
      ImagePickerUtil.selectedBlurryPhotosIds.assignAll(selectedPhotosIds);
    }
  }

  clickDelete() async {
    print('clickDelete');


    if (selectedPhotosIds.isNotEmpty) {

      final assetsToDelete = photoGroups.expand((group) =>
          group.images.where((asset) => selectedPhotosIds.contains(asset.id))
      ).toList();

      final List<String> result = await PhotoManager.editor.deleteWithIds(
        assetsToDelete.map((e) => e.id).toList(),
      );
      print('PhotoPreviewController result $result');

      if (result.length == selectedPhotosIds.length) {


        if (titleName == "Screenshots") {
          ImagePickerUtil.updatePhotoGroupDate(PhotosType.screenshots, selectedPhotosIds);
        } else if (titleName == "Blurry") {
          ImagePickerUtil.updatePhotoGroupDate(PhotosType.blurryPhotos, selectedPhotosIds);
        }
        ToastUtil.show("Delete success");
      } else {
        // 删除失败
        ToastUtil.show("Delete failed");
      }
    }
  }
}
