// User Files Edit Component
// Displays and configures user files from custom meta fields

import { __ } from '@wordpress/i18n';
import {
    InspectorControls,
    useBlockProps
} from '@wordpress/block-editor';
import {
    PanelBody,
    SelectControl,
    ToggleControl,
    TextControl,
    Spinner
} from '@wordpress/components';
import apiFetch from '@wordpress/api-fetch';
import { Fragment, useEffect, useState } from '@wordpress/element';
import MultiSelect from '../../components/MultiSelect';

const Edit = ({ attributes, setAttributes, context }) => {
    const {
        metaFieldKey,
        fieldLabel,
        showLabel,
        profileUserRoles,
        viewerRoles,
    } = attributes;

    const [metaKeys, setMetaKeys] = useState([]);
    const [isLoadingKeys, setIsLoadingKeys] = useState(false);
    const [loadError, setLoadError] = useState('');
    const [fetchedMeta, setFetchedMeta] = useState(null);

    // Get user data from context prop (Query Loop style)
    	const user = context?.['wpuf-ud/userObject'] || {
        id: 0,
        display_name: __('Sample User', 'wpuf-pro'),
        user_login: 'sampleuser',
        user_email: 'sample@example.com',
        meta: {
            'user_files': [123, 456, 789], // File IDs
            'portfolio_files': [101, 102], // File IDs
            'documents': 555, // Single file ID
            'certificates': '777' // File ID as string
        }
    };

    const blockProps = useBlockProps();

    // Roles options: convert wp-localized userRoles (array of {value,label}) to key=>label map, with fallback
    const roleOptionsBase = (() => {
        const dynamicRoles = window.wpufUserDirectory?.userRoles || [];
        if (Array.isArray(dynamicRoles) && dynamicRoles.length > 0) {
            return dynamicRoles.reduce((acc, role) => {
                if (role && role.value) {
                    acc[role.value] = role.label || role.value;
                }
                return acc;
            }, {});
        }
        return {
            all: __('All Roles', 'wpuf-pro'),
            administrator: __('Administrator', 'wpuf-pro'),
            editor: __('Editor', 'wpuf-pro'),
            author: __('Author', 'wpuf-pro'),
            contributor: __('Contributor', 'wpuf-pro'),
            subscriber: __('Subscriber', 'wpuf-pro'),
        };
    })();

    // Extend roles with special Guest option for viewer rules
    const roleOptions = {
        ...roleOptionsBase,
        guest: __('Guest', 'wpuf-pro'),
    };

    // Load user meta keys from REST API
    useEffect(() => {
        let isMounted = true;
        async function fetchMetaKeys() {
            setIsLoadingKeys(true);
            setLoadError('');
            try {
                const data = await apiFetch({ path: '/wpuf/v1/user-meta-keys' });
                if (!isMounted) return;
                const keys = Array.isArray(data?.meta_keys) ? data.meta_keys : [];
                setMetaKeys(keys);
            } catch (e) {
                if (!isMounted) return;
                setLoadError(__('Failed to load meta keys', 'wpuf-pro'));
            } finally {
                if (isMounted) setIsLoadingKeys(false);
            }
        }
        fetchMetaKeys();
        return () => {
            isMounted = false;
        };
    }, []);

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

        let value = null;
        if (user?.meta && user.meta[metaFieldKey]) {
            value = user.meta[metaFieldKey];
        } else if (fetchedMeta && fetchedMeta[metaFieldKey]) {
            value = fetchedMeta[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 [];
    };

    // If the context user lacks meta, fetch full profile data to obtain meta for preview
    useEffect(() => {
        let cancelled = false;
        async function maybeFetchUserMeta() {
            if (!user?.id || !metaFieldKey) return;
            const hasMetaInContext = (user?.meta && Object.prototype.hasOwnProperty.call(user.meta, metaFieldKey))
                || Object.prototype.hasOwnProperty.call(user || {}, metaFieldKey);
            if (hasMetaInContext) return;
            try {
                const data = await apiFetch({ path: `/wpuf/v1/user-profile/${user.id}?context=edit` });
                if (cancelled) return;
                if (data && data.meta) {
                    setFetchedMeta(data.meta);
                }
            } catch (_) {
                // ignore preview fetch errors
            }
        }
        maybeFetchUserMeta();
        return () => { cancelled = true; };
    }, [user?.id, metaFieldKey]);

    const fileData = getFileData();
    const hasFiles = Array.isArray(fileData) && fileData.length > 0;

    // Restrict by selected profile roles (editor preview)
    const selectedRoles = Array.isArray(profileUserRoles) && profileUserRoles.length ? profileUserRoles : ['all'];
    const userRoles = Array.isArray(user?.roles) ? user.roles : [];
    const roleAllowed = selectedRoles.includes('all') || userRoles.some((r) => selectedRoles.includes(r));
    // Viewer roles are enforced on frontend; allow in preview to avoid confusion
    const selectedViewerRoles = Array.isArray(viewerRoles) && viewerRoles.length ? viewerRoles : ['all'];
    const viewerAllowed = true;

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

    const displayLabel = getDisplayLabel();

    // Helper function to get file icon based on file type
    const getFileIcon = (fileType) => {
        // Add null check to prevent error when fileType is undefined
        if (!fileType || typeof fileType !== 'string') {
            // Default file icon when type is not available
            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>
            );
        }

        if (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 (like the attached image)
        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>
        );
    };

    return (
        <Fragment>
            <InspectorControls>
                <PanelBody title={__('File Settings', 'wpuf-pro')} initialOpen={true}>
                    <div style={{ marginBottom: '12px' }}>
                        <label className="components-base-control__label">{__('Meta Key', 'wpuf-pro')}</label>
                        {isLoadingKeys ? (
                            <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                                <Spinner />
                                <span>{__('Loading meta keys…', 'wpuf-pro')}</span>
                            </div>
                        ) : (
                            <SelectControl
                                value={metaFieldKey}
                                options={[{ label: __('Select a meta key', 'wpuf-pro'), value: '' }, ...metaKeys.map((key) => ({ label: key, value: key }))]}
                                onChange={(value) => setAttributes({ metaFieldKey: value })}
                                __next40pxDefaultSize={true}
                                __nextHasNoMarginBottom={true}
                            />
                        )}
                        {loadError ? <p className="components-base-control__help" style={{ color: 'var(--wp-admin-theme-color-d)' }}>{loadError}</p> : null}
                    </div>

                    <TextControl
                        label={__('Meta Key Label', 'wpuf-pro')}
                        value={fieldLabel}
                        onChange={(value) => setAttributes({ fieldLabel: value })}
                        placeholder={displayLabel}
                        help={__('Leave empty to auto-generate from meta key', 'wpuf-pro')}
                        __next40pxDefaultSize={true}
                        __nextHasNoMarginBottom={true}
                    />

                    <ToggleControl
                        label={__('Show Label', 'wpuf-pro')}
                        checked={showLabel}
                        onChange={(value) => setAttributes({ showLabel: value })}
                        __nextHasNoMarginBottom={true}
                    />
                </PanelBody>
                <PanelBody title={__('Visibility', 'wpuf-pro')} initialOpen={false}>
                    <div style={{ marginBottom: '12px' }}>
                        <label className="components-base-control__label">{__('Profile User Role', 'wpuf-pro')}</label>
                        <MultiSelect
                            options={roleOptions}
                            value={selectedRoles}
                            onChange={(value) => setAttributes({ profileUserRoles: value })}
                            placeholder={__('All Roles', 'wpuf-pro')}
                            sortable={false}
                            searchable={true}
                        />
                        <p className="components-base-control__help">{__('Show this field only for users with these roles.', 'wpuf-pro')}</p>
                    </div>

                    <div style={{ marginBottom: '12px' }}>
                        <label className="components-base-control__label">{__('Viewer Role', 'wpuf-pro')}</label>
                        <MultiSelect
                            options={roleOptions}
                            value={selectedViewerRoles}
                            onChange={(value) => setAttributes({ viewerRoles: value })}
                            placeholder={__('All Roles', 'wpuf-pro')}
                            sortable={false}
                            searchable={true}
                        />
                        <p className="components-base-control__help">{__('Show this field only to viewers with these roles. Include "Guest" for non-logged-in users.', 'wpuf-pro')}</p>
                    </div>
                </PanelBody>
            </InspectorControls>

            <div {...blockProps}>
                <div className="wpuf-user-files">
                    {hasFiles && roleAllowed && viewerAllowed ? (
                        <div className="wpuf-files-content">
                            {showLabel && displayLabel && (
                                <div className="wpuf-files-label">
                                    {displayLabel}
                                </div>
                            )}

                            <div className="files-grid !wpuf-grid !wpuf-grid-cols-2 sm:!wpuf-grid-cols-3 md:!wpuf-grid-cols-4 !wpuf-gap-3">
                                {fileData.map((file, index) => (
                                    <div key={index} className="file-item !wpuf-relative !wpuf-group">
                                        <div className="!wpuf-block !wpuf-no-underline">
                                            {file.type && file.type.startsWith('image/') ? (
                                                <div className="file-preview !wpuf-w-full !wpuf-rounded-lg !wpuf-overflow-hidden !wpuf-transition-all !wpuf-duration-200 group-hover:!wpuf-scale-105">
                                                    <img src={file.url} alt={file.name} className="!wpuf-w-full !wpuf-object-cover" />
                                                </div>
                                            ) : (
                                                <div className="file-preview !wpuf-w-full !wpuf-h-28 !wpuf-bg-gray-700 !wpuf-rounded-lg !wpuf-flex !wpuf-flex-col !wpuf-items-center !wpuf-justify-center !wpuf-text-white !wpuf-font-bold !wpuf-text-sm hover:!wpuf-bg-gray-500 !wpuf-transition-all !wpuf-duration-200 group-hover:!wpuf-scale-105">
                                                    <div className="!wpuf-text-2xl !wpuf-mb-1">
                                                        {getFileIcon(file.type)}
                                                    </div>
                                                    <span>{file.type ? file.type.split('/')[1].toUpperCase() : 'FILE'}</span>
                                                </div>
                                            )}
                                        </div>
                                        <div className="file-info !wpuf-mt-2">
                                            <div className="file-name !wpuf-text-xs !wpuf-text-gray-700 !wpuf-text-center !wpuf-truncate !wpuf-font-medium">
                                                {file.name}
                                            </div>
                                        </div>
                                    </div>
                                ))}
                            </div>
                        </div>
                    ) : (!roleAllowed ? (
                        <div className="wpuf-files-empty">
                            {__('Hidden for this user role.', 'wpuf-pro')}
                        </div>
                    ) : !metaFieldKey ? (
                        <div className="wpuf-files-empty">
                            {__('Select a meta field key in the sidebar.', 'wpuf-pro')}
                        </div>
                    ) : (
                        <div className="wpuf-files-empty">
                            {__('No files found or empty field.', 'wpuf-pro')}
                        </div>
                    ))}
                </div>
            </div>
        </Fragment>
    );
};

export default Edit;
