/** @odoo-module **/
// Fusion Claims - Preview Button Widget
// Copyright 2026 Nexa Systems Inc.
// License OPL-1

import { registry } from "@web/core/registry";
import { Component } from "@odoo/owl";
import { useService } from "@web/core/utils/hooks";
import { DocumentPreviewDialog } from "./document_preview";

class PreviewButtonComponent extends Component {
    static template = "fusion_claims.PreviewButtonWidget";
    static props = { "*": true };

    setup() {
        this.dialog = useService("dialog");
        this.notification = useService("notification");
    }

    onClick() {
        const record = this.props.record;
        if (!record || !record.data) {
            this.notification.add("No document to preview.", { type: "warning" });
            return;
        }

        const attField = record.data.attachment_id;
        let attachmentId = null;
        if (Array.isArray(attField)) {
            attachmentId = attField[0];
        } else if (attField && typeof attField === "object" && attField.id) {
            attachmentId = attField.id;
        } else if (typeof attField === "number") {
            attachmentId = attField;
        }

        const fileName = record.data.file_name || "Document Preview";

        if (!attachmentId) {
            this.notification.add("No document to preview.", { type: "warning" });
            return;
        }

        this.dialog.add(DocumentPreviewDialog, {
            attachmentId: attachmentId,
            title: fileName,
        });
    }
}

registry.category("view_widgets").add("preview_button", {
    component: PreviewButtonComponent,
});
