const b2bking_settings_purchaseorder = window.wc.wcSettings.getSetting( 'B2BKing_Purchase_Order_Gateway_data', {} );
const b2bking_purchaseorder_label = window.wp.htmlEntities.decodeEntities( b2bking_settings_purchaseorder.title ) || window.wp.i18n.__( 'Purchase Order', 'b2bking' );


const b2bking_purchaseorder_content = () => {
    const description = window.wp.htmlEntities.decodeEntities(
        b2bking_settings_purchaseorder.description || ''
    );

    // Create a text input element with name and ID set to 'po_number_field'
    const inputField = window.wp.element.createElement('input', {
        type: 'text',
        placeholder: '', // You can change the placeholder text
        name: 'po_number_field',
        id: 'po_number_field'
    });

    // Create a container for the description and the input field
    return window.wp.element.createElement(
        'div',
        null,
        description,
        inputField
    );
};

const { createElement, useState, useEffect, useRef } = wp.element;
const { decodeEntities } = wp.htmlEntities;
const { __ } = wp.i18n;
const { registerPaymentMethod } = wc.wcBlocksRegistry;
const { ValidatedTextInput } = wc.blocksCheckout;

const Content = ({ eventRegistration, emitResponse }) => {
    const [poNumber, setPONumber] = useState('');
    const [attachmentId, setAttachmentId] = useState('');
    const [isHighlighted, setIsHighlighted] = useState(false);
    const [selectedFile, setSelectedFile] = useState(null);
    const fileInputRef = useRef(null);
    const { onPaymentProcessing } = eventRegistration;

    useEffect(() => {
        const unsubscribe = onPaymentProcessing(() => {
            if (b2bking_po_settings.po_number_required && !poNumber) {
                return {
                    type: emitResponse.responseTypes.ERROR,
                    message: __('Please enter your PO Number.', 'b2bking'),
                };
            }

            if (b2bking_po_settings.allow_po_document && b2bking_po_settings.po_document_required && !attachmentId) {
                return {
                    type: emitResponse.responseTypes.ERROR,
                    message: __('Please upload a PO document.', 'b2bking'),
                };
            }

            const paymentMethodData = { po_number_field: poNumber };
            if (attachmentId) {
                paymentMethodData.po_document_attachment_id = attachmentId;
            }
            return {
                type: emitResponse.responseTypes.SUCCESS,
                meta: { paymentMethodData },
            };
        });

        return () => unsubscribe();
    }, [poNumber, attachmentId, emitResponse.responseTypes, onPaymentProcessing]);

    function uploadFile(file) {
        if (!file) return;
        setSelectedFile(file.name);
        setAttachmentId('');
        var formData = new FormData();
        formData.append('action', 'b2bking_checkout_ajax_file_upload');
        formData.append('security', b2bking_po_settings.security);
        formData.append('file', file);
        fetch(b2bking_po_settings.ajaxurl, { method: 'POST', body: formData })
            .then(function(r) { return r.text(); })
            .then(function(id) { if (parseInt(id) > 0) setAttachmentId(id.trim()); });
    }

    function handleDragOver(e) {
        e.preventDefault();
        e.stopPropagation();
        setIsHighlighted(true);
    }

    function handleDragLeave(e) {
        e.preventDefault();
        e.stopPropagation();
        setIsHighlighted(false);
    }

    function handleDrop(e) {
        e.preventDefault();
        e.stopPropagation();
        setIsHighlighted(false);
        var file = e.dataTransfer.files[0];
        if (file) uploadFile(file);
    }

    function handleFileInputChange(e) {
        var file = e.target.files[0];
        if (file) uploadFile(file);
    }

    function handleRemove(e) {
        e.stopPropagation();
        setSelectedFile(null);
        setAttachmentId('');
        if (fileInputRef.current) fileInputRef.current.value = '';
    }

    const cloudSvg = createElement('svg', {
        xmlns: 'http://www.w3.org/2000/svg', width: '50', height: '65', fill: 'none', viewBox: '0 0 88 88'
    },
        createElement('path', { stroke: '#aaaaaa', strokeLinecap: 'round', strokeLinejoin: 'round', strokeWidth: '4', d: 'M55 63.214h13.063c9.453 0 17.187-5.02 17.187-14.369 0-9.348-9.11-14.002-16.5-14.369C67.222 19.856 56.547 10.964 44 10.964c-11.86 0-19.497 7.87-22 15.675-10.313.98-19.25 7.542-19.25 18.287 0 10.746 9.281 18.288 20.625 18.288H33' }),
        createElement('path', { stroke: '#aaaaaa', strokeLinecap: 'round', strokeLinejoin: 'round', strokeWidth: '4', d: 'm55 43.964-11-11-11 11m11 33.072V35.714' })
    );

    const fileList = selectedFile ? createElement('ul', { id: 'b2bkingfilelist' },
        createElement('li', {},
            selectedFile + ' ',
            createElement('button', {
                type: 'button',
                onClick: handleRemove,
                dangerouslySetInnerHTML: { __html: '<svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" fill="none" viewBox="0 0 36 36"><g clip-path="url(#a)"><path fill="#575757" d="m19.61 18 4.86-4.86a1 1 0 0 0-1.41-1.41l-4.86 4.81-4.89-4.89a1 1 0 0 0-1.41 1.41L16.78 18 12 22.72a1 1 0 1 0 1.41 1.41l4.77-4.77 4.74 4.74a1 1 0 0 0 1.41-1.41L19.61 18Z"/><path fill="#575757" d="M18 34a16 16 0 1 1 0-32 16 16 0 0 1 0 32Zm0-30a14 14 0 1 0 0 28 14 14 0 0 0 0-28Z"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h36v36H0z"/></clipPath></defs></svg>' }
            })
        )
    ) : null;

    const fileUpload = b2bking_po_settings.allow_po_document ? createElement('p', { className: 'form-row form-row-wide' },
        createElement('label', { style: { marginTop: '10px', display: 'block' } },
            b2bking_po_settings.po_document_required
                ? [__('Upload Document', 'b2bking'), createElement('span', { className: 'required', key: 'req' }, ' *')]
                : __('Upload Document (optional)', 'b2bking')
        ),
        createElement('div', {
            className: 'b2bking-drop-area' + (isHighlighted ? ' highlight' : ''),
            onDragEnter: handleDragOver,
            onDragOver: handleDragOver,
            onDragLeave: handleDragLeave,
            onDrop: handleDrop,
            onClick: function() { if (fileInputRef.current) fileInputRef.current.click(); }
        },
            cloudSvg,
            __('Drag & Drop a file here or click to upload', 'b2bking'),
            createElement('input', {
                type: 'file',
                accept: b2bking_po_settings.accept || 'image/*, application/pdf',
                ref: fileInputRef,
                onChange: handleFileInputChange,
                style: { display: 'none' }
            }),
            fileList
        )
    ) : null;

    return createElement(
        wp.element.Fragment,
        {},
        createElement('p', {}, b2bking_po_settings.description),
        createElement(ValidatedTextInput, {
            id: "po_number_field",
            label: __('P.O. Number', 'b2bking'),
            value: poNumber,
            onChange: (value) => setPONumber(value),
            required: b2bking_po_settings.po_number_required,
        }),
        fileUpload
    );
};

// Ensure the rest of the payment method registration logic remains unchanged


const B2bking_Purchase_Order_Block_Gateway = {
    name: 'B2BKing_Purchase_Order_Gateway',
    label: b2bking_purchaseorder_label,
    content: createElement(Content, {}),
    edit: createElement(Content, {}),
    canMakePayment: () => true,
    ariaLabel: b2bking_purchaseorder_label,
    supports: {
        features: b2bking_settings_purchaseorder.supports,
    },
};

window.wc.wcBlocksRegistry.registerPaymentMethod( B2bking_Purchase_Order_Block_Gateway );

