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

class VgaGallery extends StatelessWidget {
  final List<VgaImage> images;

  const VgaGallery({super.key, required this.images});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("VGA Image Gallery")),
      backgroundColor: Colors.black,
      body: GridView.builder(
        gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
          maxCrossAxisExtent: 150,
          crossAxisSpacing: 10,
          mainAxisSpacing: 10,
        ),
        itemCount: images.length,
        itemBuilder: (context, index) {
          return Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                "Index: $index\n${images[index].width} x ${images[index].height}",
                style: const TextStyle(color: Colors.white, fontSize: 12),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 8),
              Expanded(
                child: Center(
                  child: CustomPaint(
                    painter: VgaPainter(image: images[index]),
                    // Scale it up so tiny fonts are readable
                    size: Size(
                      images[index].width * 2.0,
                      images[index].height * 2.0,
                    ),
                  ),
                ),
              ),
            ],
          );
        },
      ),
    );
  }
}

class VgaPainter extends CustomPainter {
  final VgaImage image;
  VgaPainter({required this.image});

  @override
  void paint(Canvas canvas, Size size) {
    int planeWidth = image.width ~/ 4;
    int planeSize = planeWidth * image.height;

    double pixelW = size.width / image.width;
    double pixelH = size.height / image.height;
    final Paint paint = Paint()..isAntiAlias = false;

    for (int y = 0; y < image.height; y++) {
      for (int x = 0; x < image.width; x++) {
        int plane = x % 4;
        int sx = x ~/ 4;
        int colorByte =
            image.pixels[(plane * planeSize) + (y * planeWidth) + sx];

        if (colorByte != 255) {
          int abgr = ColorPalette.vga32Bit[colorByte];

          // Extract the bytes
          int r = abgr & 0xFF;
          int g = (abgr >> 8) & 0xFF;
          int b = (abgr >> 16) & 0xFF;
          int a = (abgr >> 24) & 0xFF;

          // Repack them as ARGB for Flutter's Color object
          int argb = (a << 24) | (r << 16) | (g << 8) | b;

          paint.color = Color(argb);
          canvas.drawRect(
            Rect.fromLTWH(x * pixelW, y * pixelH, pixelW + 0.5, pixelH + 0.5),
            paint,
          );
        }
      }
    }
  }

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