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

import '../services/setting_service.dart';
import 'login_aware_cached_network_image.dart';

final _shownImageUrls = <String>{};

class ImageControl extends StatefulWidget {
  final String imageUrl;
  final double? width;
  final double? height;
  final Function()? onTap;
  final Function()? onDoubleTap;
  final Icon? iconOverride;
  final String altText;

  const ImageControl({
    super.key,
    required this.imageUrl,
    this.iconOverride,
    this.width,
    this.height,
    this.onTap,
    this.onDoubleTap,
    this.altText = '',
  });

  @override
  State<ImageControl> createState() => _ImageControlState();
}

class _ImageControlState extends State<ImageControl> {
  void showImage() {
    _shownImageUrls.add(widget.imageUrl);
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    final shown = !context.watch<SettingsService>().lowBandwidthMode ||
        _shownImageUrls.contains(widget.imageUrl);
    late final Widget image;
    if (shown) {
      _shownImageUrls.add(widget.imageUrl);
      image = LoginAwareCachedNetworkImage(
        imageUrl: widget.imageUrl,
        width: widget.width,
        height: widget.height,
      );
    } else {
      final icon = widget.iconOverride ??
          const Icon(
            Icons.image,
          );
      image = SizedBox(
        width: widget.width,
        height: widget.height,
        child: Stack(
          children: [
            SizedBox(
              width: widget.width,
              height: widget.height,
              child: Card(
                  color: Colors.black12,
                  shape: const RoundedRectangleBorder(),
                  child: icon),
            ),
            Positioned(
              child: SizedBox(
                width: widget.width,
                height: widget.height,
                child: Padding(
                  padding: const EdgeInsets.all(3.0),
                  child: Text(
                    widget.altText,
                    textAlign: TextAlign.center,
                    maxLines: 5,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              ),
            ),
          ],
        ),
      );
    }
    return GestureDetector(
      onTap: shown ? widget.onTap : showImage,
      child: image,
    );
  }
}
