import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:image_gallery_saver_plus/image_gallery_saver_plus.dart';
import 'package:screenshot/screenshot.dart';

import '../../../../config/translations/strings_enum.dart';
import '../../../../utils/device_manager.dart';
import '../../../components/ix_snackbar.dart';
import '../../../routes/app_pages.dart';
import '../widgets/precode_save_dialog.dart';

class PrecodeController extends GetxController {
  // Pre Code 数据
  final preCode = '673 888 888 999'.obs;

  // 是否显示完整代码
  final isPreviewMode = false.obs;

  // 截图控制器
  final screenshotController = ScreenshotController();

  // UID
  String get uid => DeviceManager.getCacheDeviceId();

  // 是否是Premium用户
  final isPremium = true.obs;

  // 切换预览模式
  void togglePreview() {
    isPreviewMode.value = !isPreviewMode.value;
  }

  // 获取显示的代码（隐藏或完整）
  String get displayCode {
    if (isPreviewMode.value) {
      return preCode.value;
    } else {
      // 隐藏中间部分，只显示前3位和后3位
      final parts = preCode.value.split(' ');
      if (parts.length >= 3) {
        return '${parts[0]} ****** ${parts[parts.length - 1]}';
      }
      return preCode.value;
    }
  }

  // 复制代码
  void copyCode() {
    Clipboard.setData(ClipboardData(text: preCode.value));
    IXSnackBar.showIXSnackBar(
      title: Strings.copied.tr,
      message: Strings.copied.tr,
    );
  }

  // 发送到邮箱
  void sendToEmail() {
    Get.toNamed(Routes.PRECODE_SENDEMAIL);
  }

  // 保存本地副本 - 显示弹窗
  void saveLocalCopy() {
    Get.bottomSheet(
      PrecodeSaveDialog(controller: this),
      isScrollControlled: true,
    );
  }

  // 保存截图到相册
  Future<void> saveToGallery() async {
    try {
      // 截图
      final imageBytes = await screenshotController.capture();

      if (imageBytes == null) {
        IXSnackBar.showIXSnackBar(
          title: Strings.error.tr,
          message: Strings.failedCaptureScreenshot.tr,
        );
        return;
      }

      // 保存到相册
      final result = await ImageGallerySaverPlus.saveImage(
        imageBytes,
        quality: 100,
        name: 'flashlink_precode_${DateTime.now().millisecondsSinceEpoch}',
      );

      if (result['isSuccess'] == true) {
        // 显示成功提示
        IXSnackBar.showIXSnackBar(
          title: "",
          message: Strings.imageSavedToAlbum.tr,
        );
      } else {
        IXSnackBar.showIXErrorSnackBar(
          title: Strings.error.tr,
          message: Strings.failedSaveImage.tr,
        );
      }
    } catch (e) {
      IXSnackBar.showIXErrorSnackBar(
        title: Strings.error.tr,
        message: '${Strings.failedToSave.tr}: $e',
      );
    }
  }
}
