import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import '../models/photo.dart';
import '../services/media_scanner.dart';
import '../core/theme.dart';

class PhotoThumbnail extends StatefulWidget {
  final Photo photo;
  final double size;

  const PhotoThumbnail({
    super.key,
    required this.photo,
    this.size = 100,
  });

  @override
  State<PhotoThumbnail> createState() => _PhotoThumbnailState();
}

class _PhotoThumbnailState extends State<PhotoThumbnail> with AutomaticKeepAliveClientMixin {
  late Future<Uint8List> _thumbnailFuture;

  @override
  void initState() {
    super.initState();
    if (widget.photo.contentUri.startsWith('content://')) {
      _thumbnailFuture = MediaScanner.getThumbnail(widget.photo.contentUri);
    } else {
      _thumbnailFuture = File(widget.photo.contentUri).readAsBytes();
    }
  }

  @override
  bool get wantKeepAlive => true; // Keep thumbnail loaded in scroll lists

  @override
  Widget build(BuildContext context) {
    super.build(context);
    final theme = Theme.of(context);
    final isDark = theme.brightness == Brightness.dark;

    return Container(
      width: widget.size,
      height: widget.size,
      clipBehavior: Clip.antiAlias,
      decoration: BoxDecoration(
        color: isDark ? AppColors.darkBgTertiary : AppColors.lightBgTertiary,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(
          color: isDark ? AppColors.darkBorder : AppColors.lightBorder,
          width: 1,
        ),
      ),
      child: FutureBuilder<Uint8List>(
        future: _thumbnailFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(
              child: SizedBox(
                width: 20,
                height: 20,
                child: CircularProgressIndicator(strokeWidth: 2),
              ),
            );
          } else if (snapshot.hasError) {
            return Center(
              child: Icon(
                Icons.broken_image,
                size: 24,
                color: theme.hintColor,
              ),
            );
          } else if (snapshot.hasData) {
            return Image.memory(
              snapshot.data!,
              fit: BoxFit.cover,
              width: widget.size,
              height: widget.size,
            );
          }
          return const SizedBox.shrink();
        },
      ),
    );
  }
}
