import 'dart:async';
import 'dart:io';
import 'dart:typed_data';

import 'package:crop_your_image/crop_your_image.dart';
import 'package:flip_card/flip_card_controller.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:pin_code_fields/pin_code_fields.dart';
import 'package:uuid/uuid.dart';
import 'package:wallpaperx/common/components/dialog/remind_dialog.dart';
import 'package:wallpaperx/common/components/easy_loading.dart';
import 'package:wallpaperx/common/components/navigation_bar/custom_appbar.dart';
import 'package:wallpaperx/common/components/photo_picker_bottom_sheet.dart';
import 'package:wallpaperx/common/components/view_state_widget.dart';
import 'package:wallpaperx/common/storage/custom_data.dart';
import 'package:wallpaperx/common/utils/device_info_util.dart';
import 'package:wallpaperx/common/utils/log_print.dart';
import 'package:wallpaperx/common/utils/permission_util.dart';
import 'package:wallpaperx/common/utils/shared_util.dart';
import 'package:wallpaperx/entity/image_model.dart';
import 'package:wallpaperx/routes/app_pages.dart';

class CustomController extends GetxController {
  static CustomController get to => Get.find<CustomController>();
  late ScrollController scrollController;
  late ViewState viewState;
  RxList customList = [].obs;

  String password = "";

  TextEditingController textEditingController = TextEditingController();

  late StreamController<ErrorAnimationType> errorController;

  late FlipCardController flipCardController;

  bool hasError = false;

  @override
  void onInit() {
    super.onInit();
    errorController = StreamController<ErrorAnimationType>();
    scrollController = ScrollController();
    flipCardController = FlipCardController();
    password = UPCache.getInstance().get("custom_password")??"";
    getCustomList();
  }

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

  void getCustomList() {
    customList.clear();
    customList.addAll(CustomData().getWallpaperData().reversed.toList());
    LogPrint.d(customList.length);
    refreshCustomList();
  }

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

  /// 点击壁纸
  void toImageDetail(int position) {
    Get.toNamed(AppPages.wallpaperDetail, arguments: {
      'position': position,
      'isSetHistory': false,
      'wallpaperList': customList,
    });
  }

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

  Future<void> toPhotos() async {
    Get.bottomSheet(
      isScrollControlled: true,
      TPhotoPickerBottomSheet(
        funCamera: () async {
          bool result =
              await PermissionUtil.checkPermission([Permission.camera]);
          if (!result) return;
          _openCameraGallery(ImageSource.camera);
        },
        funGallery: () async {
          Permission permission = Permission.photos;
          if (Platform.isAndroid) {
            int sdkInt = await DeviceInfoUtil.getAndroidSystemVersion();
            if (sdkInt <= 32) {
              permission = Permission.storage;
            } else {
              permission = Permission.photos;
            }
          }
          bool result = await PermissionUtil.checkPermission([permission]);
          if (!result) return;
          _openCameraGallery(ImageSource.gallery);
        },
      ),
    );
  }

  Future<void> _openCameraGallery(ImageSource source) async {
    final ImagePicker picker = ImagePicker();
    final XFile? photo = await picker.pickImage(source: source);
    if (photo != null) {
      final controller = CropController();
      Uint8List image = await photo.readAsBytes();
      Get.to(
        () => Scaffold(
          backgroundColor: Colors.black,
          appBar: const CustomAppbar(''),
          body: SafeArea(
            top: false,
            child: Column(
              children: [
                Expanded(
                  child: Crop(
                    baseColor: Colors.black,
                    image: image,
                    controller: controller,
                    onCropped: (image) {
                      setFile(image);
                      LogPrint.d('裁剪后的图片：${image.lengthInBytes}');
                    },
                  ),
                ),
                Row(
                  children: [
                    Expanded(child: Container()),
                    GestureDetector(
                      onTap: controller.crop,
                      child: Container(
                        margin: const EdgeInsets.symmetric(
                          horizontal: 16,
                          vertical: 46,
                        ).w,
                        padding: const EdgeInsets.symmetric(
                          horizontal: 35,
                          vertical: 8,
                        ).w,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(30.r),
                          gradient: const LinearGradient(
                            begin: Alignment.topRight,
                            end: Alignment.bottomLeft,
                            colors: [
                              Color(0xffBEEF32),
                              Color(0xff2795E5),
                              Color(0xff8041FD),
                            ],
                          ),
                        ),
                        child: Center(
                          child: Text(
                            "Apply",
                            style: TextStyle(
                                color: Colors.white,
                                fontSize: 18.sp,
                                fontWeight: FontWeight.bold),
                          ),
                        ),
                      ),
                    )
                  ],
                ),
              ],
            ),
          ),
        ),
      );
    }
  }

  Future setFile(Uint8List image) async {
    try {
      String uuid = const Uuid().v4();
      Directory directory = await getApplicationDocumentsDirectory();
      File file = File('${directory.path}/$uuid.txt');
      // 保存到文件系统
      await file.writeAsBytes(image);
      // 询问用户是否保存它
      ImageModel model = ImageModel(imageUrl: file.path);
      CustomData().setWallpaperData(model);
      Get.back();
      getCustomList();
    } catch (e) {
      toast(e.toString());
    }
  }

  Uint8List? readImage(String filePath) {
    try {
      final file = File(filePath);
      Uint8List u8 = file.readAsBytesSync();
      return u8;
    } catch (e) {
      return null;
    }
  }

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