import 'dart:io';
import 'package:flutter/material.dart';

class ImageManager extends ChangeNotifier {
  static final ImageManager _instance = ImageManager._();
  static ImageManager get instance => _instance;
  ImageManager._();

  final List<String> _images = [];
  int _currentIndex = 0;

  List<String> get images => List.unmodifiable(_images);
  int get currentIndex => _currentIndex;
  int get imageCount => _images.length;

  String get currentImagePath {
    if (_images.isEmpty) return '';
    return _images[_currentIndex];
  }

  void addImages(List<String> paths) {
    final validPaths = paths.where((p) {
      final ext = p.toLowerCase().split('.').last;
      const supported = ['png', 'jpg', 'jpeg', 'webp', 'bmp', 'gif'];
      return supported.contains(ext) && File(p).existsSync();
    }).toList();

    if (validPaths.isEmpty) return;

    _images.addAll(validPaths);

    // Precache images
    for (final path in validPaths) {
      precacheImage(FileImage(File(path)), context!);
    }

    notifyListeners();
  }

  void setCurrentIndex(int index) {
    if (index < 0 || index >= _images.length) return;
    _currentIndex = index;
    notifyListeners();
  }

  void previousImage() {
    if (_images.isEmpty) return;
    _currentIndex = (_currentIndex - 1 + _images.length) % _images.length;
    notifyListeners();
  }

  void nextImage() {
    if (_images.isEmpty) return;
    _currentIndex = (_currentIndex + 1) % _images.length;
    notifyListeners();
  }

  // Precache needs a BuildContext
  BuildContext? context;

  /// Configure image cache for high-res images
  static void configureCache() {
    PaintingBinding.instance.imageCache.maximumSize = 1000;
    PaintingBinding.instance.imageCache.maximumSizeBytes = 1024 * 1024 * 1024; // 1 GB
  }

  set buildContext(BuildContext ctx) {
    context = ctx;
  }

  void clear() {
    _images.clear();
    _currentIndex = 0;
    notifyListeners();
  }
}
