import 'package:clean/module/calendar/calendar_state.dart';
import 'package:clean/module/calendar/preview/calendar_preview_view.dart';
import 'package:clean/module/people_photo/photo_group.dart';
import 'package:flutter/Material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:intl/intl.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import '../../base/base_controller.dart';
import 'package:get/get.dart';

import '../image_picker/image_picker_util.dart';
import 'calendar_month_view.dart';

class CalendarController extends BaseController {
  final RxList<PhotoGroup> monthlyAlbums = CalendarState.monthlyAlbums;
  final RxList<AssetEntity> imageList = <AssetEntity>[].obs;
  final Rx<SortType> currentSortType = SortType.latest.obs; // 当前排序类型

  @override
  void onInit() {
    super.onInit();
    loadAssets();
  }

  // 加载并分组图片
  Future<void> loadAssets() async {
    final List<AssetEntity> result = await ImagePickerUtil.loadAssets();
    result.sort((a, b) => b.createDateTime.compareTo(a.createDateTime));
    imageList.value = result;
    updateMonthlyAssets();
  }

  // 更新按月份分组的照片
  void updateMonthlyAssets() {
    Map<String, List<AssetEntity>> groupedAssets = {};

    // 按月份分组照片
    for (var asset in imageList) {
      final monthKey = DateFormat('yyyy-MM').format(asset.createDateTime);
      groupedAssets.putIfAbsent(monthKey, () => []).add(asset);
    }

    monthlyAlbums.clear();
    groupedAssets.forEach((month, assets) {
      assets
          .sort((a, b) => b.createDateTime.compareTo(a.createDateTime)); // 时间排序
      monthlyAlbums
          .add(PhotoGroup(month: month, images: assets, isSelected: false));
    });
    // 计算
    for (var album in monthlyAlbums) {
      album.initTotalSize();
    }
    // 打印结果
    for (var album in monthlyAlbums) {
      debugPrint(
          'CalendarController month: ${album.month}, images: ${album.images.length} ,totalSize: ${album.totalSize}');
    }
  }

  // 点击月份卡片，跳转到对应月份的照片详情页
  void clickMonthCard(PhotoGroup photoGroup) {
    print("clickMonthCard photoGroup: ${photoGroup.totalSize}");

    CalendarMonthPage.start(photoGroup: photoGroup);
  }

  // 点击图片，查看该图片详情
  void clickImage(PhotoGroup photoGroup, int imageIndex) {
    print("CalendarController clickImage");

    CalendarPreviewPage.start(
        photoGroup: photoGroup,
        currentImageId: photoGroup.images[imageIndex].id);
  }

  // 排序照片列表
  void sortAssets(SortType sortType) {
    currentSortType.value = sortType; // 更新当前排序类型

    switch (sortType) {
      case SortType.latest:
        // 按月份倒序排列
        monthlyAlbums.sort((a, b) => b.month!.compareTo(a.month!));
        break;

      case SortType.oldest:
        // 按月份正序排列
        monthlyAlbums.sort((a, b) => a.month!.compareTo(b.month!));
        break;

      case SortType.largeSize:
        for (var album in monthlyAlbums) {
          print(
              "CalendarController album: ${album.month}, images: ${album.images.length} ,totalSize: ${album.totalSize}");
          album.initTotalSize();
        }
        monthlyAlbums
            .sort((a, b) => b.totalSize.value.compareTo(a.totalSize.value));
        break;

      case SortType.mostQuantity:
        // 按照片数量排序
        monthlyAlbums
            .sort((a, b) => b.images.length.compareTo(a.images.length));
        break;
    }
  }

  // 显示排序弹窗
  void clickSort() {
    showCupertinoModalPopup(
      context: Get.context!,
      builder: (context) {
        return Container(
          width: 360.w,
          decoration: ShapeDecoration(
            color: Color(0xFF131C27),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(44.r),
                topRight: Radius.circular(44.r),
              ),
            ),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              SizedBox(height: 10.h),
              Container(
                width: 57.w,
                height: 4.h,
                decoration: ShapeDecoration(
                  color: Color(0xFF242D38),
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(2)),
                ),
              ),
              SizedBox(height: 19.h),
              Text(
                'Sort By',
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w700,
                ),
              ),
              SizedBox(height: 14.h),
              // Latest
              sortOption(SortType.latest, 'Latest'),
              SizedBox(height: 14.h),
              // Oldest
              sortOption(SortType.oldest, 'Oldest'),
              SizedBox(height: 14.h),
              // Large Size
              sortOption(SortType.largeSize, 'Largest Storage Usage'),
              SizedBox(height: 14.h),
              // Most Quantity
              sortOption(SortType.mostQuantity, 'Most Quantity'),
              SizedBox(height: 55.h),
            ],
          ),
        );
      },
    );
  }

  Widget sortOption(SortType type, String title) {
    bool isSelected = currentSortType.value == type; // 判断是否是选中的排序类型
    return GestureDetector(
      onTap: () {
        Navigator.pop(Get.context!);
        sortAssets(type);
      },
      child: Container(
        width: 300.w,
        height: 50.h,
        alignment: Alignment.center,
        decoration: ShapeDecoration(
          color: isSelected ? Color(0x1C0279FB) : Color(0xFF242D38),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(14.r),
          ),
        ),
        child: Text(
          title,
          style: TextStyle(
            color:
                isSelected ? Colors.white : Colors.white.withValues(alpha: 0.8),
            fontSize: isSelected ? 16.sp : 14.sp,
            fontWeight: isSelected ? FontWeight.w700 : FontWeight.w500,
          ),
        ),
      ),
    );
  }
}

// 排序类型
enum SortType {
  latest, // 最新
  oldest, // 最旧
  largeSize, // 按文件组大小排序
  mostQuantity // 按每个月照片数量排序
}
