// 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,
    TextareaControl,
    Spinner
} from '@wordpress/components';
import apiFetch from '@wordpress/api-fetch';
import { Fragment, useEffect, useState } from '@wordpress/element';
import MultiSelect from '../../components/MultiSelect';

// Constant for "No Subscription Required" option to avoid repetition
const ALL_SUBSCRIPTIONS_OPTION = { value: 'all', label: __('No Subscription Required', 'wpuf-pro') };

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

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

    // 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 and Logged In options for viewer rules
    const roleOptions = {
        ...roleOptionsBase,
        guest: __('Guest', 'wpuf-pro'),
        logged_in: __('Logged In Users', '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;
        };
    }, []);

    // Load subscription packs from REST API
    useEffect(() => {
        let isMounted = true;
        async function fetchSubscriptionPacks() {
            setIsLoadingPacks(true);
            try {
                const data = await apiFetch({ path: '/wpuf/v1/wpuf_subscription' });
                if (!isMounted) return;
                
                // Transform response to options format
                if (data?.success && Array.isArray(data.subscriptions)) {
                    const packs = data.subscriptions
                        .filter(pack => pack.post_status === 'publish') // Only published subscriptions
                        .map(pack => ({
                            value: String(pack.ID),
                            label: pack.post_title || __('Unnamed Pack', 'wpuf-pro')
                        }));
                    
                    // Add "No Subscription Required" option at the beginning
                    setSubscriptionPacks([
                        ALL_SUBSCRIPTIONS_OPTION,
                        ...packs
                    ]);
                } else {
                    // If no subscriptions or error, just show "No Subscription Required"
                    setSubscriptionPacks([ALL_SUBSCRIPTIONS_OPTION]);
                }
            } catch (e) {
                if (!isMounted) return;
                // Handle errors gracefully - permission denied, module not available, etc.
                // Just show "No Subscription Required" option
                setSubscriptionPacks([ALL_SUBSCRIPTIONS_OPTION]);
            } finally {
                if (isMounted) setIsLoadingPacks(false);
            }
        }
        fetchSubscriptionPacks();
        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 selectedViewerSubscriptionPacks = Array.isArray(viewerSubscriptionPacks) && viewerSubscriptionPacks.length ? viewerSubscriptionPacks : ['all'];
    const viewerAllowed = true; // Preview always shows field; subscription check happens on frontend

    // 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}
                            exclusiveOptions={['all', 'logged_in']}
                        />
                        <p className="components-base-control__help">{__('Show this field only to viewers with these roles. Include "Guest" for non-logged-in users, or "Logged In Users" for any authenticated user.', 'wpuf-pro')}</p>
                    </div>

                    <div style={{ marginBottom: '12px' }}>
                        <label className="components-base-control__label">{__('Viewer Subscription Pack', 'wpuf-pro')}</label>
                        {isLoadingPacks ? (
                            <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                                <Spinner />
                                <span>{__('Loading subscription packs…', 'wpuf-pro')}</span>
                            </div>
                        ) : (
                            <MultiSelect
                                options={subscriptionPacks.reduce((acc, pack) => {
                                    acc[pack.value] = pack.label;
                                    return acc;
                                }, {})}
                                value={selectedViewerSubscriptionPacks}
                                onChange={(value) => setAttributes({ viewerSubscriptionPacks: value })}
                                placeholder={__('No Subscription Required', 'wpuf-pro')}
                                sortable={false}
                                searchable={true}
                                exclusiveOptions={['all']}
                            />
                        )}
                        <p className="components-base-control__help">{__('Show this field only to viewers with these subscription packs. Requires logged-in users.', 'wpuf-pro')}</p>
                    </div>

                    {(!selectedViewerRoles.includes('all') || !selectedViewerSubscriptionPacks.includes('all')) && (
                        <div style={{ marginBottom: '12px' }}>
                            <SelectControl
                                label={__('Access Logic', 'wpuf-pro')}
                                value={viewerAccessLogic || 'and'}
                                options={[
                                    { label: __('Require Both', 'wpuf-pro'), value: 'and' },
                                    { label: __('Require Either', 'wpuf-pro'), value: 'or' },
                                ]}
                                onChange={(value) => setAttributes({ viewerAccessLogic: value })}
                                __next40pxDefaultSize={true}
                                __nextHasNoMarginBottom={true}
                            />
                            <p className="components-base-control__help">{__('How to combine role and subscription restrictions. "Require Both" means viewer must have both a matching role AND subscription. "Require Either" means viewer needs either a matching role OR subscription.', 'wpuf-pro')}</p>
                        </div>
                    )}

                    {(!selectedViewerRoles.includes('all') || !selectedViewerSubscriptionPacks.includes('all')) && (
                        <>
                            <div style={{ marginBottom: '12px' }}>
                                <SelectControl
                                    label={__('Restriction Behavior', 'wpuf-pro')}
                                    value={fieldViewType || 'hide'}
                                    options={[
                                        { label: __('Hide completely', 'wpuf-pro'), value: 'hide' },
                                        { label: __('Show custom message', 'wpuf-pro'), value: 'show_custom_message' },
                                    ]}
                                    onChange={(value) => setAttributes({ fieldViewType: value })}
                                    __next40pxDefaultSize={true}
                                    __nextHasNoMarginBottom={true}
                                />
                                <p className="components-base-control__help">{__('What to show when viewer does not have required role or subscription.', 'wpuf-pro')}</p>
                            </div>

                            {fieldViewType === 'show_custom_message' && (
                                <div style={{ marginBottom: '12px' }}>
                                    <TextareaControl
                                        label={__('Custom Message', 'wpuf-pro')}
                                        value={customMessage || ''}
                                        onChange={(value) => {
                                            // Limit to 500 characters
                                            const limitedValue = value.length > 500 ? value.substring(0, 500) : value;
                                            setAttributes({ customMessage: limitedValue });
                                        }}
                                        placeholder={__('Enter custom message to display. You can use {login}, {register}, and {subscriptions} for dynamic content.', 'wpuf-pro')}
                                        rows={4}
                                        __next40pxDefaultSize={true}
                                        __nextHasNoMarginBottom={true}
                                    />
                                    <p className="components-base-control__help" style={{ marginTop: '4px' }}>
                                        {__('Message to display when viewer does not have required role. Use {login} and {register} for links, and {subscriptions} will show the selected subscription pack names (comma-separated).', 'wpuf-pro')}
                                        <span style={{ 
                                            display: 'block', 
                                            marginTop: '4px', 
                                            color: (customMessage?.length || 0) >= 500 ? '#d63638' : '#646970',
                                            fontSize: '12px'
                                        }}>
                                            {customMessage?.length || 0}/500 {__('characters', 'wpuf-pro')}
                                        </span>
                                    </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;
