import { __ } from '@wordpress/i18n';

const UserCustomField = ({ user, attributes, context }) => {
    const {
        metaFieldKey = '',
        fieldLabel = '',
        fieldType = 'text',
        emptyValue = '',
        multipleValues = 'comma_separated',
        dateFormat = 'F j, Y',
        imageSize = 'thumbnail',
        customImageSize = { width: 150, height: 150 },
        linkTarget = '_self',
        prefixText = '',
        suffixText = '',
        showLabel = true,
        labelPosition = 'above',
        layoutStyle = 'inline',
        profileUserRoles = ['all'],
        viewerRoles = ['all']
    } = attributes || {};

    // Get field value from user meta
    const getFieldValue = () => {
        if (!user || !metaFieldKey) return emptyValue || __('No data', 'wpuf-pro');
        
        // Check both meta object and direct user properties
        let value = null;
        
        if (user.meta && user.meta[metaFieldKey]) {
            value = user.meta[metaFieldKey];
        } else if (user[metaFieldKey]) {
            value = user[metaFieldKey];
        }
        
        if (!value) return emptyValue || __('No data', 'wpuf-pro');
        
        return value;
    };

    // Format field value based on field type
    const formatFieldValue = (value) => {
        if (!value) return emptyValue || __('No data', 'wpuf-pro');

        switch (fieldType) {
            case 'email':
                return <a href={`mailto:${value}`}>{value}</a>;
            case 'url':
                return <a href={value} target={linkTarget} rel="noopener noreferrer">{value}</a>;
            case 'date':
                try {
                    const date = new Date(value);
                    return date.toLocaleDateString('en-US', { 
                        year: 'numeric', 
                        month: 'long', 
                        day: 'numeric' 
                    });
                } catch (e) {
                    return value;
                }
            case 'image':
                return (
                    <img 
                        src={value} 
                        alt={fieldLabel || __('Custom field image', 'wpuf-pro')}
                        style={{
                            width: customImageSize.width,
                            height: customImageSize.height
                        }}
                    />
                );
            case 'file':
                return (
                    <a href={value} target={linkTarget} rel="noopener noreferrer">
                        {__('Download File', 'wpuf-pro')}
                    </a>
                );
            case 'json':
                try {
                    const parsed = JSON.parse(value);
                    return <pre>{JSON.stringify(parsed, null, 2)}</pre>;
                } catch (e) {
                    return value;
                }
            default:
                return value;
        }
    };

    // Render field with prefix/suffix
    const renderField = () => {
        const value = getFieldValue();
        const formattedValue = formatFieldValue(value);

        return (
            <div className="wpuf-custom-field-content">
                {prefixText && <span className="wpuf-field-prefix">{prefixText}</span>}
                <span className="wpuf-field-value">{formattedValue}</span>
                {suffixText && <span className="wpuf-field-suffix">{suffixText}</span>}
            </div>
        );
    };

    // Render label
    const renderLabel = () => {
        if (!showLabel || !fieldLabel) return null;

        const Tag = labelPosition === 'above' ? 'div' : 'span';
        return (
            <Tag className="wpuf-field-label">
                {fieldLabel}
            </Tag>
        );
    };

    // Check visibility based on roles
    const isVisible = () => {
        // For now, always show in block editor
        // In production, implement role-based visibility logic
        return true;
    };

    if (!isVisible()) {
        return null;
    }

    const fieldValue = getFieldValue();
    
    return (
        <div className={`wpuf-custom-field wpuf-field-${fieldType} wpuf-layout-${layoutStyle}`}>
            {!metaFieldKey ? (
                <div className="wpuf-field-placeholder">
                    <p>{__('Select a meta field key in the sidebar.', 'wpuf-pro')}</p>
                </div>
            ) : (
                <div className={`wpuf-field-wrapper wpuf-label-${labelPosition}`}>
                    {labelPosition === 'above' && renderLabel()}
                    <div className="wpuf-field-content">
                        {labelPosition === 'inline' && renderLabel()}
                        {renderField()}
                    </div>
                    {labelPosition === 'below' && renderLabel()}
                </div>
            )}
        </div>
    );
};

export default UserCustomField; 