import 'package:flutter/material.dart';
import 'package:wolf_3d_data_types/wolf_3d_data_types.dart';
import 'package:wolf_3d_entities/wolf_3d_entities.dart';
import 'package:wolf_dart/features/renderer/color_palette.dart';

class SpriteGallery extends StatelessWidget {
  final List<Sprite> sprites;

  const SpriteGallery({super.key, required this.sprites});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Sprite Gallery"),
        automaticallyImplyLeading: true,
      ),
      backgroundColor: Colors.black,
      body: GridView.builder(
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 8, // 8 sprites per row
        ),
        itemCount: sprites.length,
        itemBuilder: (context, index) {
          // --- Check which enemy owns this sprite ---
          String label = "Idx: $index";
          for (final enemy in EnemyType.values) {
            if (enemy.claimsSpriteIndex(index)) {
              // Appends the enum name (e.g., "guard", "dog")
              label += "\n${enemy.name}";
              break;
            }
          }

          return Column(
            children: [
              Text(
                label,
                style: const TextStyle(color: Colors.white, fontSize: 10),
                textAlign: TextAlign.center,
              ),
              Expanded(
                child: CustomPaint(
                  painter: SingleSpritePainter(sprite: sprites[index]),
                  size: const Size(64, 64),
                ),
              ),
            ],
          );
        },
      ),
    );
  }
}

class SingleSpritePainter extends CustomPainter {
  final Sprite sprite;
  SingleSpritePainter({required this.sprite});

  @override
  void paint(Canvas canvas, Size size) {
    double pixelSize = size.width / 64;
    for (int x = 0; x < 64; x++) {
      for (int y = 0; y < 64; y++) {
        int colorByte = sprite[x][y];
        if (colorByte != 255) {
          // Skip transparency
          canvas.drawRect(
            Rect.fromLTWH(x * pixelSize, y * pixelSize, pixelSize, pixelSize),
            Paint()..color = ColorPalette.vga[colorByte],
          );
        }
      }
    }
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => false;
}
