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

const UserFiles = ({ user, attributes, context }) => {
    const {
        metaFieldKey = '',
        fieldLabel = '',
        showLabel = true,
        profileUserRoles = ['all'],
        viewerRoles = ['all']
    } = attributes || {};

    // Get file data from user meta
    const getFileData = () => {
        if (!user || !metaFieldKey) return [];

        // 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 [];

        // Parse file data - expect array of file IDs or JSON string
        if (Array.isArray(value)) {
            return value;
        }

        if (typeof value === 'string') {
            try {
                const decoded = JSON.parse(value);
                if (Array.isArray(decoded)) {
                    return decoded;
                }
            } catch (e) {
                // Not JSON, treat as single file ID
                return [value];
            }
        }

        if (typeof value === 'number') {
            return [value];
        }

        return [];
    };

    // Get field label
    const getDisplayLabel = () => {
        if (fieldLabel) return fieldLabel;
        return metaFieldKey ? metaFieldKey.replace(/_/g, ' ').replace(/\b\w/g, (l) => l.toUpperCase()) : '';
    };

    // Helper function to get file icon based on file type
    const getFileIcon = (fileType) => {
        if (fileType && fileType.startsWith('image/')) {
            return (
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M21 19V5C21 3.9 20.1 3 19 3H5C3.9 3 3 3.9 3 5V19C3 20.1 3.9 21 5 21H19C20.1 21 21 20.1 21 19ZM8.5 13.5L11 16.51L14.5 12L19 18H5L8.5 13.5Z" fill="currentColor"/>
                </svg>
            );
        }

        // Default file icon
        return (
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M14 2H6C4.9 2 4 2.9 4 4V20C4 21.1 4.89 22 5.99 22H18C19.1 22 20 21.1 20 20V8L14 2ZM18 20H6V4H13V9H18V20Z" fill="currentColor"/>
            </svg>
        );
    };

    // 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 fileData = getFileData();
    const hasFiles = fileData.length > 0;
    const displayLabel = getDisplayLabel();

    return (
        <div className="wpuf-user-files">
            {!metaFieldKey ? (
                <div className="wpuf-files-empty">
                    {__('Select a meta field key in the sidebar.', 'wpuf-pro')}
                </div>
            ) : !hasFiles ? (
                <div className="wpuf-files-empty">
                    {__('No files found or empty field.', 'wpuf-pro')}
                </div>
            ) : (
                <div className="wpuf-files-content">
                    {showLabel && displayLabel && (
                        <div className="wpuf-files-label">
                            {displayLabel}
                        </div>
                    )}

                    <ul role="list" className="wpuf-grid wpuf-grid-cols-2 wpuf-gap-x-4 wpuf-gap-y-8 sm:wpuf-grid-cols-3 sm:wpuf-gap-x-6 lg:wpuf-grid-cols-4 xl:wpuf-gap-x-8">
                        {fileData.map((fileId, index) => {
                            // For block editor preview, show sample file data based on file ID
                            const sampleFiles = {
                                123: { name: 'document.pdf', type: 'application/pdf', size: '2.5 MB' },
                                456: { name: 'presentation.pptx', type: 'application/vnd.openxmlformats-officedocument.presentationml.presentation', size: '4.1 MB' },
                                789: { name: 'spreadsheet.xlsx', type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', size: '1.8 MB' },
                                101: { name: 'project-specs.docx', type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', size: '3.2 MB' },
                                102: { name: 'design-mockup.psd', type: 'image/vnd.adobe.photoshop', size: '15.7 MB' },
                                555: { name: 'certificate.pdf', type: 'application/pdf', size: '1.2 MB' },
                                777: { name: 'portfolio.zip', type: 'application/zip', size: '8.5 MB' }
                            };

                            const fileInfo = sampleFiles[fileId] || {
                                name: `File ${fileId}`,
                                type: 'application/octet-stream',
                                size: 'Unknown'
                            };

                            return (
                                <li key={index} className="wpuf-relative">
                                    <div className="wpuf-group wpuf-overflow-hidden wpuf-rounded-lg focus-within:wpuf-outline focus-within:wpuf-outline-2 focus-within:wpuf-outline-offset-2 focus-within:wpuf-outline-indigo-600">
                                        <div className="wpuf-aspect-[10/7] wpuf-rounded-lg wpuf-flex wpuf-items-center wpuf-justify-center">
                                            <div className="wpuf-text-gray-500">
                                                {getFileIcon(fileInfo.type)}
                                            </div>
                                        </div>
                                        <a href="#" className="wpuf-absolute wpuf-inset-0 wpuf-focus:wpuf-outline-none" onClick={(e) => e.preventDefault()}>
                                            <span className="wpuf-sr-only">
                                                {__('View details for', 'wpuf-pro')} {fileInfo.name}
                                            </span>
                                        </a>
                                    </div>
                                    <p className="wpuf-pointer-events-none wpuf-mt-2 wpuf-block wpuf-truncate wpuf-text-sm wpuf-font-medium wpuf-text-gray-900">
                                        {fileInfo.name}
                                    </p>
                                    <p className="wpuf-pointer-events-none wpuf-block wpuf-text-sm wpuf-font-medium wpuf-text-gray-500">
                                        {fileInfo.size}
                                    </p>
                                </li>
                            );
                        })}
                    </ul>
                </div>
            )}
        </div>
    );
};

export default UserFiles;
