import 'dart:io';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:gal/gal.dart';
import 'package:kaer_with_panels/app/utils/kr_common_util.dart';
import 'package:kaer_with_panels/app/widgets/dialogs/hi_dialog.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher.dart';

class HIAntiLostController extends GetxController {

  Future<void> saveImage() async {
    // KRCommonUtil.kr_showLoading(message: "正在保存...");
    try {
      // Load image from assets
      final ByteData data =
          await rootBundle.load('assets/images/lost-share-image.png');
      final Uint8List pngBytes = data.buffer.asUint8List();

      if (Platform.isMacOS || Platform.isWindows || Platform.isLinux) {
        // Desktop: Use FilePicker to save file
        String? outputFile = await FilePicker.platform.saveFile(
          dialogTitle: '保存图片',
          fileName: 'Hi快联系方式',
          type: FileType.custom,
          allowedExtensions: ['png'],
        );

        if (outputFile != null) {
          final file = File(outputFile);
          await file.writeAsBytes(pngBytes);
          KRCommonUtil.kr_showToast("已保存至: $outputFile");
        }
      } else {
        // Mobile: Use Gal to save to gallery
        // Check permission
        if (!await Gal.hasAccess()) {
          await Gal.requestAccess();
        }

        await Gal.putImageBytes(pngBytes);
        HIDialog.show(
          message: "已保存至系统相册",
        );
      }
    } catch (e) {
      debugPrint("Save image error: $e");
      if (e is GalException) {
        if (e.type == GalExceptionType.accessDenied) {
          HIDialog.show(
            title: "提示",
            message: "请到：设置-应用-Hi快vpn-相册权限-允许保存相片打开保存图片权限",
            confirmText: "去设置",
            cancelText: "取消",
            onConfirm: () => openAppSettings(),
          );
        } else {
          KRCommonUtil.kr_showToast("保存失败: ${e.type.name}");
        }
      } else {
        KRCommonUtil.kr_showToast("保存失败: $e");
      }
    } finally {
      //KRCommonUtil.kr_hideLoading();
    }
  }

  void openTwitter() async {
    // Try Deep Link first
    final Uri appUrl = Uri.parse('twitter://user?screen_name=hifasttech');
    final Uri webUrl = Uri.parse('https://x.com/hifasttech');

    try {
      if (await canLaunchUrl(appUrl)) {
        await launchUrl(appUrl);
      } else {
        // Fallback to web
        if (!await launchUrl(webUrl, mode: LaunchMode.externalApplication)) {
          KRCommonUtil.kr_showToast("无法打开链接");
        }
      }
    } catch (e) {
      debugPrint("Open Twitter error: $e");
      // Fallback to web if anything goes wrong
      try {
        if (!await launchUrl(webUrl, mode: LaunchMode.externalApplication)) {
          KRCommonUtil.kr_showToast("无法打开链接");
        }
      } catch (e) {
        KRCommonUtil.kr_showToast("无法打开链接");
      }
    }
  }
}
