import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:wallpaperx/generated/assets.dart';

class ImageNetworkWidget extends StatelessWidget {
  const ImageNetworkWidget({
    super.key,
    this.width,
    this.height,
    this.radius = 0.0,
    required this.url,
    this.fit = BoxFit.cover,
    this.aspectRatio,
    this.placeholder,
    this.errorWidget,
  });

  final double? width;
  final double? height;
  final double radius;
  final String? url;
  final BoxFit fit;
  final double? aspectRatio;
  final Widget? placeholder;
  final Widget? errorWidget;

  @override
  Widget build(BuildContext context) {
    if (aspectRatio != null) {
      return AspectRatio(
        aspectRatio: aspectRatio ?? 0.5,
        child: ClipRRect(
          borderRadius: BorderRadius.circular(radius),
          child: CachedNetworkImage(
            width: width,
            height: height,
            imageUrl: '$url',
            fit: fit,
            placeholder: (context, url) {
              return placeholder ??
                  _placeholderWidget(Assets.iconPlaceholderImage);
            },
            errorWidget: (context, url, error) {
              return errorWidget ?? _placeholderWidget(Assets.iconImgErrorType);
            },
          ),
        ),
      );
    }
    return ClipRRect(
      borderRadius: BorderRadius.circular(radius),
      child: CachedNetworkImage(
        width: width,
        height: height,
        imageUrl: '$url',
        fit: fit,
        placeholder: (context, url) {
          return placeholder ?? _placeholderWidget(Assets.iconPlaceholderImage);
        },
        errorWidget: (context, url, error) {
          return errorWidget ?? _placeholderWidget(Assets.iconImgErrorType);
        },
      ),
    );
  }

  Widget _placeholderWidget(String imgName) {
    return Container(
      color: Colors.grey,
      child: Image.asset(
        imgName,
        color: Colors.white,
      ),
    );
  }
}
