import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/saf_permission_state.dart';

/// SAF 存储服务
/// 负责管理通过 SAF 授权的文件夹访问
class SafStorageService {
  static final SafStorageService _instance = SafStorageService._internal();
  factory SafStorageService() => _instance;
  SafStorageService._internal();

  static const MethodChannel _channel = MethodChannel(
    'com.lxh.battery_health/saf',
  );
  static const String _prefKeySafUri = 'saf_storage_uri';
  String? _cachedUri;

  /// 初始化，从 SharedPreferences 恢复 URI
  Future<void> init() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      _cachedUri = prefs.getString(_prefKeySafUri);
      if (kDebugMode) {
        print('[SAF] 初始化，缓存 URI: $_cachedUri');
      }
    } catch (e) {
      if (kDebugMode) {
        print('[SAF] 初始化失败: $e');
      }
      _cachedUri = null;
    }
  }

  /// 获取当前授权状态（简化版，直接根据缓存判断）
  Future<SafPermissionState> getPermissionState() async {
    if (_cachedUri == null || _cachedUri!.isEmpty) {
      return SafPermissionState.unauthorized;
    }
    // 直接返回 authorized，相信缓存
    return SafPermissionState.authorized;
  }

  /// 请求 SAF 授权（引导用户选择文件夹）
  Future<SafAuthorizationResult> requestPermission() async {
    try {
      final String? uriString = await _channel.invokeMethod('selectFolder');

      if (uriString == null || uriString.isEmpty) {
        return SafAuthorizationResult.denied();
      }

      _cachedUri = uriString;
      await _saveUri(uriString);

      if (kDebugMode) {
        print('[SAF] 授权成功，URI: $uriString');
      }

      return SafAuthorizationResult.success(uriString);
    } catch (e) {
      if (kDebugMode) {
        print('[SAF] 授权失败: $e');
      }
      return SafAuthorizationResult.error('授权失败: $e');
    }
  }

  /// 🟢 将 URI 传递给 Kotlin 端（用于恢复 safUri）
  Future<bool> restoreUri() async {
    if (_cachedUri == null || _cachedUri!.isEmpty) {
      if (kDebugMode) {
        print('[SAF] restoreUri: 缓存 URI 为空');
      }
      return false;
    }
    try {
      final bool? result = await _channel.invokeMethod('restoreUri', {
        'uri': _cachedUri,
      });
      if (result == true) {
        if (kDebugMode) {
          print('[SAF] restoreUri 成功: $_cachedUri');
        }
        return true;
      } else {
        if (kDebugMode) {
          print('[SAF] restoreUri 失败: 返回 false');
        }
        return false;
      }
    } catch (e) {
      if (kDebugMode) {
        print('[SAF] restoreUri 异常: $e');
      }
      return false;
    }
  }

  /// 检查指定日期的日志文件是否存在
  Future<bool> logFileExists(String fileName) async {
    final state = await getPermissionState();
    if (state != SafPermissionState.authorized) return false;
    try {
      final files = await listFiles();
      return files.contains(fileName);
    } catch (e) {
      return false;
    }
  }

  /// 读取日志文件内容（返回行列表）
  Future<List<String>> readLogFile(String fileName) async {
    // 🟢 先尝试恢复 URI
    await restoreUri();

    final state = await getPermissionState();
    if (state != SafPermissionState.authorized) return [];

    try {
      final String? content = await _channel.invokeMethod('readLogFile', {
        'fileName': fileName,
      });
      if (content == null || content.isEmpty) return [];
      return content.split('\n');
    } catch (e) {
      if (kDebugMode) {
        print('[SAF] 读取文件失败: $e');
      }
      return [];
    }
  }

  /// 获取文件夹中的文件列表
  Future<List<String>> listFiles() async {
    // 🟢 先尝试恢复 URI
    await restoreUri();

    final state = await getPermissionState();
    if (state != SafPermissionState.authorized) return [];

    try {
      final result = await _channel.invokeMethod('listFiles');
      if (result is List) {
        return result.cast<String>();
      }
      return [];
    } catch (e) {
      if (kDebugMode) {
        print('[SAF] 列出文件失败: $e');
      }
      return [];
    }
  }

  /// 验证授权是否有效（简化版）
  Future<bool> validatePermission() async {
    final state = await getPermissionState();
    return state == SafPermissionState.authorized;
  }

  /// 清除缓存
  void _clearCache() {
    _cachedUri = null;
    _saveUri(null);
  }

  /// 保存 URI 到 SharedPreferences
  Future<void> _saveUri(String? uri) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      if (uri != null && uri.isNotEmpty) {
        await prefs.setString(_prefKeySafUri, uri);
        if (kDebugMode) {
          print('[SAF] 保存 URI 成功: $uri');
        }
      } else {
        await prefs.remove(_prefKeySafUri);
        if (kDebugMode) {
          print('[SAF] 清除 URI');
        }
      }
    } catch (e) {
      if (kDebugMode) {
        print('[SAF] 保存 URI 失败: $e');
      }
    }
  }

  /// 获取缓存的 URI（用于调试）
  String? get cachedUri => _cachedUri;
}
