import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SvgCache {
  static final SvgCache _instance = SvgCache._internal();
  factory SvgCache() => _instance;
  SvgCache._internal();

  final Dio _dio = Dio();
  Directory? _cacheDir;

  Future<void> init() async {
    if (kIsWeb) {
      // Web doesn't need directory initialization
      return;
    }

    final appDir = await getApplicationDocumentsDirectory();
    _cacheDir = Directory('${appDir.path}/svg_cache');
    if (!await _cacheDir!.exists()) {
      await _cacheDir!.create(recursive: true);
    }
  }

  Future<String?> getCachedPath(String url) async {
    if (kIsWeb) {
      return await _getWebCachedPath(url);
    }

    final fileName = _getFileName(url);
    final file = File('${_cacheDir!.path}/$fileName');
    return await file.exists() ? file.path : null;
  }

  Future<String> cacheSvg(String url) async {
    if (kIsWeb) {
      return await _cacheWebSvg(url);
    }

    final fileName = _getFileName(url);
    final file = File('${_cacheDir!.path}/$fileName');
    final response = await _dio.get(
      url,
      options: Options(responseType: ResponseType.plain),
    );
    await file.writeAsString(response.data);
    return file.path;
  }

  Future<String?> _getWebCachedPath(String url) async {
    final prefs = await SharedPreferences.getInstance();
    final fileName = _getFileName(url);
    return prefs.containsKey('svg_cache_$fileName')
        ? 'web_cache_$fileName'
        : null;
  }

  Future<String> _cacheWebSvg(String url) async {
    final response = await _dio.get(
      url,
      options: Options(responseType: ResponseType.plain),
    );
    final fileName = _getFileName(url);
    final prefs = await SharedPreferences.getInstance();

    // Store SVG data in SharedPreferences for web
    await prefs.setString('svg_cache_$fileName', response.data);
    return 'web_cache_$fileName';
  }

  String _getFileName(String url) {
    return url.split('/').last.replaceAll(RegExp(r'[^a-zA-Z0-9._-]'), '_');
  }
}
