// User Custom Field Edit Component
// Displays and configures user custom fields with various display options

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: {
            'phone_number': '+1 (555) 123-4567',
            'location': 'New York, NY',
            'company': 'Sample Company',
            'job_title': 'Sample Job Title',
            'website': 'https://example.com',
            'bio': 'This is a sample bio for the custom field block.',
            'social_facebook': 'https://facebook.com/sampleuser',
            'social_twitter': 'https://twitter.com/sampleuser',
            'custom_field_1': 'Sample Custom Value 1',
            'custom_field_2': 'Sample Custom Value 2',
            'custom_field_3': 'Sample Custom Value 3'
        }
    };

    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 field value
    const getFieldValue = () => {
        if (!metaFieldKey) return '';
        if (user?.meta && user.meta[metaFieldKey]) {
            return user.meta[metaFieldKey];
        }
        if (user && user[metaFieldKey]) {
            return user[metaFieldKey];
        }
        if (fetchedMeta && fetchedMeta[metaFieldKey]) {
            return fetchedMeta[metaFieldKey];
        }
        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 rawValue = getFieldValue();
    const fieldValue = typeof rawValue === 'string' ? rawValue : (rawValue != null ? String(rawValue) : '');
    const hasValue = fieldValue && fieldValue.trim() !== '';

    // 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();

    return (
        <Fragment>
            <InspectorControls>
                <PanelBody title={__('Custom Field 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-custom-field">
                    {hasValue && roleAllowed && viewerAllowed ? (
                        <div className="wpuf-field-content">
                            <div className="wpuf-field-text">
                                {showLabel && displayLabel && (
                                    <span className="wpuf-field-label">
                                        {displayLabel}:
                                    </span>
                                )}

                                <span className="wpuf-field-value">
                                    {fieldValue}
                                </span>
                            </div>
                        </div>
                    ) : (!roleAllowed ? (
                        <div className="wpuf-field-empty">
                            {__('Hidden for this user role.', 'wpuf-pro')}
                        </div>
                    ) : (
                        <div className="wpuf-field-empty">
                            {__('Field not found or empty.', 'wpuf-pro')}
                        </div>
                    ))}
                </div>
            </div>
        </Fragment>
    );
};

export default Edit;
