import 'dart:convert';
import 'dart:developer';
import 'dart:math' as m;
import 'dart:typed_data';

import 'package:flutter/cupertino.dart';
import 'package:mnemo_cards/features/packs/images_holder.dart';
import 'package:mnemo_cards/theme/themes.dart';

import '../../../di/locator.dart';

class TestImageWidget extends StatefulWidget {
  final TestImage _testImage;

  const TestImageWidget(this._testImage, {super.key});

  @override
  State<StatefulWidget> createState() => _TestImageWidgetState();
}

class _TestImageWidgetState extends State<TestImageWidget> {
  TestImage get _testImage => widget._testImage;
  bool same = false;
  Widget? cached;

  @override
  void didUpdateWidget(TestImageWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    same = oldWidget._testImage == _testImage;
  }

  Future<Widget> _preloadImage() async {
    try {
      // final cache = _TestImageCache();
      // final cachedImage = cache.image(_testImage);
      // if (cachedImage != null) {
      //   return cachedImage;
      // }
      final imageProvider = await _testImage.loadImage();
      if (imageProvider == null) {
        return SizedBox.shrink();
      }
      // cache.setImage(_testImage, imageProvider);
      return Image(image: imageProvider);
    } catch (e) {
      log('Cant load image ${_testImage}packId: $e');
    }
    return SizedBox();
  }

  @override
  Widget build(BuildContext context) {
    // final cache = _TestImageCache();
    if (same && cached != null) {
      return cached!;
    }
    return FutureBuilder(
      future: _preloadImage(),
      // initialData: cache.image(_testImage),
      builder: (_, s) {
        if (s.data == null) {
          return Container(
            alignment: Alignment.center,
          );
        }
        cached = Container(
          clipBehavior: Clip.antiAlias,
          decoration: BoxDecoration(
            color: white,
            borderRadius: BorderRadius.circular(12),
          ),
          child: s.data,
        );
        return cached!;
      },
    );
  }
}

class TestImage {
  final String data;
  final String key;

  TestImage({
    required this.data,
    required this.key,
  });

  @override
  bool operator ==(Object other) {
    return other is TestImage && key == other.key;
  }

  Future<ImageProvider?> loadImage() async {
    if (data.length > 50) {
      Uint8List? bytes;
      try {
        bytes = base64Decode(data);
        return MemoryImage(bytes);
      } catch (e) {
        log('Cant decode base64 test image');
        return null;
      }
    } else if (data.contains(':')) {
      final packId = data.split(':').first;
      final path = data.split(':').last;
      return await locator.testManager.loadImage(packId, path);
    } else {
      return data.memoryImage;
    }
  }

  TestImage.image(String image)
      : data = image,
        key = image.substring(0, m.min(image.length, 50));
}

// class _TestImageCache {
//   static final _instance = _TestImageCache._();
//
//   _TestImageCache get instance => _instance;
//
//   factory _TestImageCache() => _instance;
//
//   _TestImageCache._();
//
//   Map<TestImage, Image> _images = {};
//
//   Image? image(TestImage key) {
//     return _images[key];
//   }
//
//   Image? setImage(TestImage key, ImageProvider provider) {
//     return _images[key] = Image(image: provider);
//   }
//
//   void clear() => _images.clear();
// }
