import 'dart:io';

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 SimilarPhotoController extends BaseController {
  final RxList<PhotoGroup> photoGroups = <PhotoGroup>[].obs;
  final RxDouble selectedFilesSize = 0.0.obs;
  RxInt selectedFileCount = 0.obs;

  Future<void> getSelectedFilesSize() 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> groupTitle, int imageIndex) {
    final group = _getGroupByImages(groupTitle);
    final image = group.images[imageIndex];
    final selected = !group.selectedImages[imageIndex];

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

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

    selectedFileCount.value = ImagePickerUtil.selectedSimilarPhotosIds.length;
    getSelectedFilesSize();
  }

  void clickImage(List<AssetEntity> images, int imageIndex) {
    final group = _getGroupByImages(images);
    final image = group.images[imageIndex];
    PhotoPreviewPage.start(PhotosType.similarPhotos, image.id);
  }

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

    for (var image in group.images) {
      _updateSelectedSimilarPhotosIds(image.id, newValue);
    }
    selectedFileCount.value = ImagePickerUtil.selectedSimilarPhotosIds.length;
    getSelectedFilesSize();
  }

  PhotoGroup _getGroupByImages(List<AssetEntity> images) {
    return photoGroups.firstWhere((g) => g.images == images);
  }

  void _updateSelectedSimilarPhotosIds(String photoId, bool isSelected) {
    if (isSelected) {
      ImagePickerUtil.selectedSimilarPhotosIds.add(photoId);
    } else {
      ImagePickerUtil.selectedSimilarPhotosIds.remove(photoId);
    }
  }

  void restoreSelections() async {
    final selectedIds = ImagePickerUtil.selectedSimilarPhotosIds.toSet();
    for (var group in photoGroups) {
      for (int i = 0; i < group.images.length; i++) {
        group.selectedImages[i] = selectedIds.contains(group.images[i].id);
      }
      group.isSelected.value =
          group.selectedImages.every((selected) => selected);
    }
    await getSelectedFilesSize();
    selectedFileCount.value = selectedIds.length;
  }

  @override
  void onInit() {
    super.onInit();
    loadSimilarPhotos();
    restoreSelections();
  }

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

    photoGroups.addAll(
      ImagePickerUtil.similarPhotos.where((group) => group.isNotEmpty).map(
        (group) {
          return PhotoGroup(
            isSelected: true,
            images: group,
          );
        },
      ),
    );
    // 每组第一张图片不选中，其余选中
    for (var group in photoGroups) {
      for (int i = 0; i < group.images.length; i++) {
        group.selectedImages[i] = i == 0 ? false : true;

        _updateSelectedSimilarPhotosIds(group.images[i].id, i != 0);
      }
    }

    selectedFileCount.value = ImagePickerUtil.selectedSimilarPhotosIds.length;
    getSelectedFilesSize();
  }

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

    if (ImagePickerUtil.selectedSimilarPhotosIds.isNotEmpty) {
      final assetsToDelete = photoGroups
          .expand((group) => group.images.where((asset) =>
              ImagePickerUtil.selectedSimilarPhotosIds.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 == ImagePickerUtil.selectedSimilarPhotosIds.length) {
        for (var group in photoGroups) {
          group.images.removeWhere((element) =>
              ImagePickerUtil.selectedSimilarPhotosIds.contains(element.id));
        }
        ImagePickerUtil.updatePhotoGroupDate(
            PhotosType.similarPhotos, ImagePickerUtil.selectedSimilarPhotosIds);
        ToastUtil.show("Delete success");
      } else {
        // 删除失败
        ToastUtil.show("Delete failed");
      }
    }
  }

  // 修改视图构建方法，使用 AssetEntity 而不是文件路径
  AssetEntity? getAssetById(String id) {
    for (var group in ImagePickerUtil.similarPhotos) {
      for (var asset in group) {
        if (asset.id == id) {
          return asset;
        }
      }
    }
    return null;
  }
}
