import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:shimmer/shimmer.dart';

Widget cachedImageNetwork(
  String url,
  BoxFit boxFit, [
  BorderRadius borderRadius = const BorderRadius.all(Radius.circular(16.0)),
  double width = double.infinity,
  double height = double.infinity,
]) {
  return ClipRRect(
    borderRadius: borderRadius,
    child: url.contains('https://')
        ? CachedNetworkImage(
            imageUrl: url,
            fit: boxFit,
            imageBuilder: (context, imageProvider) => Container(
              width: width,
              height: height,
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: imageProvider,
                  fit: boxFit,
                ),
              ),
            ),
            placeholder: (context, url) => Container(
              width: width,
              height: height,
              child: Shimmer.fromColors(
                baseColor: Colors.grey.shade300,
                highlightColor: Colors.grey.shade100,
                child: Icon(
                  Icons.image,
                  size: 30.sp,
                  color: Colors.grey.withOpacity(0.5),
                ),
              ),
            ),
            errorWidget: (context, url, error) => ErrorImageWidget(
              boxFit: boxFit,
              width: width,
              height: height,
              borderRadius: borderRadius,
            ),
          )
        : ErrorImageWidget(
            boxFit: boxFit,
            width: width,
            height: height,
            borderRadius: borderRadius,
          ),
  );
}

class ErrorImageWidget extends StatelessWidget {
  late final BoxFit boxFit;
  late final width;
  late final height;
  late final borderRadius;

  ErrorImageWidget({
    required this.boxFit,
    required this.width,
    required this.height,
    required this.borderRadius,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: new BoxDecoration(
        borderRadius: borderRadius,
      ),
      width: this.width,
      height: this.height,
      child: Icon(
        Icons.broken_image,
        size: 30.sp,
        color: Colors.grey.withOpacity(0.5),
      ),
    );
  }
}
