import { __ } from '@wordpress/i18n';
import { IMaskInput } from 'react-imask';
import { useEffect, useState } from "react";

export const PaymentDocument = ({ gateway, cpf, processProps }) => {
    const label = __('CPF do Comprador', 'vindi');
    const [formattedCpf, setFormattedCpf] = useState(cpf);
    const [showDocument, setShowDocument] = useState(false);

    useEffect(() => {
        const checkPersonType = () => {
            const personField = 
                document.querySelector('[name="vindi-pagamentos/billing_persontype"]') ||
                document.querySelector('#vindi-pagamentos__billing_persontype') ||
                document.querySelector('select[id*="billing_persontype"]') ||
                document.querySelector('[id^="vindi-pagamentos"][id*="persontype"]');
            
            if (personField && personField.value == 2) {
                setShowDocument(true);
            } else {
                setShowDocument(false);
            }
        };

        checkPersonType();
        const observer = new MutationObserver(checkPersonType);
        observer.observe(document.body, {
            childList: true,
            subtree: true
        });

        const handleChange = (e) => {
            if (e.target && (
                e.target.name === 'vindi-pagamentos/billing_persontype' ||
                e.target.id === 'vindi-pagamentos__billing_persontype' ||
                e.target.id?.includes('billing_persontype')
            )) {
                checkPersonType();
            }
        };

        document.addEventListener('change', handleChange);
        
        // Listener para evento customizado (disparado pelo PersonTypeFallback)
        document.addEventListener('add_checkout_block_fields', checkPersonType);

        // Cleanup
        return () => {
            observer.disconnect();
            document.removeEventListener('change', handleChange);
            document.removeEventListener('add_checkout_block_fields', checkPersonType);
        };
    }, []);

    useEffect(() => {
        processProps({ gateway, cpf: formattedCpf });
    }, [gateway, formattedCpf, cpf, processProps]);

    return (
        <>
            <div className={`vindi-pagamentos-document ${!showDocument ? 'vindi-pagamentos-document-hidden': ''}`}>
                <label htmlFor={`document-${gateway}`}>{label}<span>*</span></label>
                <div>
                    <IMaskInput
                        mask={'000.000.000-00'}
                        type="text"
                        aria-label={label}
                        id={`document-${gateway}`}
                        value={formattedCpf}
                        onAccept={(value, mask) => setFormattedCpf(value)}
                        className="wc-vindi-customer-document wvp-block-field"
                    />
                </div>
            </div>
        </>
    );
};
