using Gtk;
using Gdk;

class AttachmentPreview : Gtk.Box {
    public signal void remove_requested();
    
    private File file;
    private string upload_guid;
    private string? attachment_guid = null;
    private bool is_completed = false;
    
    private Overlay overlay;
    private Image picture;
    private Spinner spinner;
    private Button remove_button;
    
    public AttachmentPreview(File file, string upload_guid) {
        Object(orientation: Orientation.VERTICAL, spacing: 0);
        this.file = file;
        this.upload_guid = upload_guid;
        
        setup_ui();
        load_image();
    }
    
    private void setup_ui() {
        set_size_request(100, 100);
        add_css_class("attachment-preview");
        
        overlay = new Overlay();
        overlay.set_size_request(100, 100);
        append(overlay);
        
        // Image preview
        picture = new Image();
        overlay.set_child(picture);
        
        // Loading spinner
        spinner = new Spinner();
        spinner.set_halign(Align.CENTER);
        spinner.set_valign(Align.CENTER);
        spinner.set_size_request(24, 24);
        spinner.start();
        overlay.add_overlay(spinner);
        
        // Remove button
        remove_button = new Button();
        remove_button.set_icon_name("window-close-symbolic");
        remove_button.add_css_class("circular");
        remove_button.add_css_class("destructive-action");
        remove_button.set_halign(Align.END);
        remove_button.set_valign(Align.START);
        remove_button.set_margin_top(4);
        remove_button.set_margin_end(4);
        remove_button.set_size_request(20, 20);
        remove_button.clicked.connect(() => {
            remove_requested();
        });
        overlay.add_overlay(remove_button);
    }
    
    private void load_image() {
        try {
            picture.set_from_file(file.get_path());
        } catch (Error e) {
            warning("Failed to load image preview: %s", e.message);
            
            // Show a placeholder icon if image loading fails
            var icon = new Image.from_icon_name("image-x-generic");
            icon.set_pixel_size(48);
            overlay.set_child(icon);
        }
    }
    
    public void set_completed(string attachment_guid) {
        this.attachment_guid = attachment_guid;
        this.is_completed = true;
        
        spinner.stop();
        spinner.set_visible(false);
        
        // Optionally change visual state to indicate completion
        add_css_class("completed");
    }
    
    public string? get_attachment_guid() {
        return attachment_guid;
    }
    
    public bool get_is_completed() {
        return is_completed;
    }
}