import SwiftUI

struct AsyncImageView: View {
    let imagePath: String
    let targetSize: CGSize

    @State private var image: UIImage?

    var body: some View {
        ZStack {
            Rectangle()
                .fill(Color(.systemGray6))

            if let image = image {
                Image(uiImage: image)
                    .resizable()
                    .scaledToFill()
                    .transition(.opacity.animation(.easeInOut(duration: 0.3)))
            } else {
                Image(systemName: "photo")
                    .font(.system(size: 24))
                    .foregroundColor(Color(.systemGray3))
            }
        }
        .frame(width: targetSize.width, height: targetSize.height)
        .clipped()
        .cornerRadius(8)
        .task(id: imagePath) {
            if self.image != nil {
                self.image = nil
            }

            self.image = await ImageManager.shared.loadThumbnail(
                fromPath: imagePath,
                targetSize: targetSize
            )
        }
    }
}
