// User Avatar Edit Component
// Displays and configures user avatar with various display options

import { __ } from '@wordpress/i18n';
import {
    InspectorControls,
    useBlockProps
} from '@wordpress/block-editor';
import {
    PanelBody,
    SelectControl,
    ToggleControl,
    TextControl,
    RangeControl
} from '@wordpress/components';
import { Fragment, useState, useEffect } from '@wordpress/element';

import './style.css';

const Edit = ({ attributes, setAttributes, context }) => {
    const {
        avatarSize,
        avatarShape,
        fallbackType,
        customSize
    } = attributes;

    // 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'
    };

    const blockProps = useBlockProps();

    // State for real avatar data
    const [avatarData, setAvatarData] = useState(null);
    const [isLoading, setIsLoading] = useState(false);

    // Function to get user initials from display name
    const getUserInitials = (displayName) => {
        if (!displayName) return 'U';

        const names = displayName.trim().split(' ');
        if (names.length === 1) {
            return names[0].charAt(0).toUpperCase();
        }

        return (names[0].charAt(0) + names[names.length - 1].charAt(0)).toUpperCase();
    };

    // Function to render avatar with initials
    const renderAvatarWithInitials = (user, size) => {
        const initials = getUserInitials(user.display_name);
        const sizeClass = size === 'small' ? 'wpuf-avatar--small' :
                         size === 'medium' ? 'wpuf-avatar--medium' :
                         size === 'large' ? 'wpuf-avatar--large' :
                         size === 'xlarge' ? 'wpuf-avatar--xlarge' :
                         'wpuf-avatar--custom';
        
        const shapeClass = `wpuf-avatar--${avatarShape}`;

        return (
            <div
                className={`wpuf-avatar--initials ${sizeClass} ${shapeClass}`}
                style={size === 'custom' ? { '--wpuf-avatar-size': `${customSize}px` } : {}}
            >
                <span className="wpuf-avatar-initials-text">{initials}</span>
            </div>
        );
    };

    // Function to fetch real avatar data
    const fetchAvatarData = async (userId, size, fallbackType) => {
        if (userId === 0) {
            return null; // Sample user, no real data
        }

        try {
            setIsLoading(true);
            const response = await fetch(`/wp-json/wpuf-pro/v1/user/${userId}/avatar?size=${size}&fallback_type=${fallbackType}`);
            
            if (response.ok) {
                const data = await response.json();
                return data;
            } else {
                console.warn('Failed to fetch avatar data:', response.status);
                return null;
            }
        } catch (error) {
            console.warn('Error fetching avatar data:', error);
            return null;
        } finally {
            setIsLoading(false);
        }
    };

    // Calculate display size
    const getDisplaySize = () => {
        const sizeMap = {
            'small': 32,
            'medium': 96,
            'large': 150,
            'xlarge': 300,
            'custom': customSize
        };
        return sizeMap[avatarSize] || 96;
    };

    // Fetch avatar data when user, size, or fallback type changes
    useEffect(() => {
        if (user.id > 0) {
            const displaySize = getDisplaySize();
            fetchAvatarData(user.id, displaySize, fallbackType).then(setAvatarData);
        } else {
            setAvatarData(null);
        }
    }, [user.id, avatarSize, customSize, fallbackType]);

    // Get avatar URL from real data or fallback
    const getAvatarUrl = () => {
        if (user.id === 0) {
            // Sample user - show placeholder
            const size = getDisplaySize();
            return `https://via.placeholder.com/${size}/007cba/ffffff?text=SU`;
        }

        if (avatarData && avatarData.url) {
            return avatarData.url;
        }

        return null;
    };

    const avatarUrl = getAvatarUrl();

    return (
        <Fragment>
            <InspectorControls>
                <PanelBody title={__('Avatar Settings', 'wpuf-pro')} initialOpen={true}>
                    <SelectControl
                        label={__('Avatar Size', 'wpuf-pro')}
                        value={avatarSize}
                        options={[
                            { label: __('Small (32px)', 'wpuf-pro'), value: 'small' },
                            { label: __('Medium (96px)', 'wpuf-pro'), value: 'medium' },
                            { label: __('Large (150px)', 'wpuf-pro'), value: 'large' },
                            { label: __('Extra Large (300px)', 'wpuf-pro'), value: 'xlarge' },
                            { label: __('Custom', 'wpuf-pro'), value: 'custom' }
                        ]}
                        onChange={(value) => setAttributes({ avatarSize: value })}
                        __next40pxDefaultSize={true}
                        __nextHasNoMarginBottom={true}
                    />

                    {avatarSize === 'custom' && (
                        <RangeControl
                            label={__('Custom Size (px)', 'wpuf-pro')}
                            value={customSize}
                            onChange={(value) => setAttributes({ customSize: value })}
                            min={32}
                            max={600}
                            step={1}
                            help={__('Set the custom size in pixels', 'wpuf-pro')}
                            __next40pxDefaultSize={true}
                            __nextHasNoMarginBottom={true}
                        />
                    )}

                    <SelectControl
                        label={__('Avatar Shape', 'wpuf-pro')}
                        value={avatarShape}
                        options={[
                            { label: __('Circle', 'wpuf-pro'), value: 'circle' },
                            { label: __('Square', 'wpuf-pro'), value: 'square' },
                            { label: __('Rounded', 'wpuf-pro'), value: 'rounded' }
                        ]}
                        onChange={(value) => setAttributes({ avatarShape: value })}
                        __next40pxDefaultSize={true}
                        __nextHasNoMarginBottom={true}
                    />

                    <SelectControl
                        label={__('Fallback Type', 'wpuf-pro')}
                        value={fallbackType}
                        options={[
                            { label: __('Gravatar', 'wpuf-pro'), value: 'gravatar' },
                            { label: __('Initials', 'wpuf-pro'), value: 'initials' }
                        ]}
                        onChange={(value) => setAttributes({ fallbackType: value })}
                        help={__('WPUF Profile Photo Field (wpuf_profile_photo) will always take priority.', 'wpuf-pro')}
                        __next40pxDefaultSize={true}
                        __nextHasNoMarginBottom={true}
                    />
                </PanelBody>
            </InspectorControls>

            <div {...blockProps}>
                <div className="wpuf-user-avatar">
                    <div className="wpuf-avatar-container">
                        {isLoading ? (
                            <div className="wpuf-avatar-loading">
                                <span>{__('Loading...', 'wpuf-pro')}</span>
                            </div>
                        ) : avatarUrl ? (
                            // Show custom profile photo if available (regardless of fallback type)
                            <img
                                src={avatarUrl}
                                alt={avatarData?.alt || user.display_name}
                                className={`wpuf-avatar--image wpuf-avatar--${avatarSize} wpuf-avatar--${avatarShape}`}
                                style={avatarSize === 'custom' ? { '--wpuf-avatar-size': `${customSize}px` } : {}}
                            />
                        ) : fallbackType === 'initials' ? (
                            // Show initials if no custom photo and fallback type is initials
                            renderAvatarWithInitials(user, avatarSize)
                        ) : (
                            // Show initials as final fallback
                            renderAvatarWithInitials(user, avatarSize)
                        )}
                    </div>
                </div>
            </div>
        </Fragment>
    );
};

export default Edit;
