// User Cover Photo Edit Component
// Displays and configures user cover photo with various display options

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

import './style.css';

const Edit = ({ attributes, setAttributes, context }) => {
    const {
        coverHeight,
        coverWidth,
        customWidthValue,
        customWidthUnit,
        fitType,
        fallbackType,
        placeholderColor
    } = 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();

    // Extract border styles from attributes.style.border to apply to the cover photo element
    // WordPress stores border styles in attributes.style.border
    const borderStyles = {};
    if (attributes.style?.border) {
        const border = attributes.style.border;
        if (border.radius) borderStyles.borderRadius = border.radius;
        if (border.width) borderStyles.borderWidth = border.width;
        if (border.color) borderStyles.borderColor = border.color;
        if (border.style) borderStyles.borderStyle = border.style;
    }

    // Build inline styles for custom width
    const customWidthStyle = coverWidth === 'custom' ? {
        width: customWidthUnit === 'px'
            ? `${customWidthValue || 800}px`
            : `${customWidthValue || 100}%`,
        maxWidth: customWidthUnit === 'px'
            ? `${customWidthValue || 800}px`
            : `${customWidthValue || 100}%`,
        margin: '0 auto'
    } : {};
    
    const coverPhotoStyles = {
        height: `${coverHeight}px`,
        ...customWidthStyle,
        ...borderStyles,
    };

    // State for real cover photo data
    const [coverPhotoData, setCoverPhotoData] = useState(null);
    const [isLoading, setIsLoading] = useState(false);

    // Function to fetch real cover photo data
    const fetchCoverPhotoData = async (userId) => {
        if (userId === 0) {
            return null; // Sample user, no real data
        }

        try {
            setIsLoading(true);
            const response = await fetch(`/wp-json/wpuf-pro/v1/user/${userId}/cover-photo`);

            if (response.ok) {
                const data = await response.json();
                return data;
            } else {
                console.warn('Failed to fetch cover photo data:', response.status);
                return null;
            }
        } catch (error) {
            console.warn('Error fetching cover photo data:', error);
            return null;
        } finally {
            setIsLoading(false);
        }
    };

    // Calculate display dimensions for placeholder
    const getDisplayDimensions = () => {
        let width = 1200; // default for full-width
        if (coverWidth === 'custom') {
            // For custom width, use the value directly (px) or convert % to approximate px
            if (customWidthUnit === 'px') {
                width = customWidthValue || 800;
            } else {
                // For %, estimate based on typical viewport (1200px base)
                width = Math.round((customWidthValue || 100) * 12); // 100% = ~1200px
            }
        }
        return { height: coverHeight, width };
    };

    // Fetch cover photo data when user changes
    useEffect(() => {
        if (user.id > 0) {
            fetchCoverPhotoData(user.id).then(setCoverPhotoData);
        } else {
            setCoverPhotoData(null);
        }
    }, [user.id]);

    // Get cover photo URL or fallback
    const getCoverPhotoUrl = () => {
        if (user.id === 0) {
            // Sample user - show placeholder
            const { width, height } = getDisplayDimensions();
            return `https://via.placeholder.com/${width}x${height}/${placeholderColor.replace('#', '')}/6b7280?text=Cover+Photo`;
        }

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

        return null;
    };

    const coverPhotoUrl = getCoverPhotoUrl();
    const { width, height } = getDisplayDimensions();

    // Render fallback content
    const renderFallback = () => {
        if (fallbackType === 'placeholder') {
            return (
                <div
                    className="wpuf-cover-photo__placeholder"
                    style={{ backgroundColor: placeholderColor }}
                >
                    <span className="wpuf-cover-photo__placeholder-text">
                        {__('No Cover Photo', 'wpuf-pro')}
                    </span>
                </div>
            );
        } else if (fallbackType === 'solid') {
            return (
                <div
                    className="wpuf-cover-photo__solid"
                    style={{ backgroundColor: placeholderColor }}
                />
            );
        }
        return null;
    };

    const coverPhotoContent = (
        <div
            className={`wpuf-cover-photo wpuf-cover-photo--${coverWidth} wpuf-cover-photo--${fitType}`}
            style={coverPhotoStyles}
        >
            <div className="wpuf-cover-photo__container">
                {isLoading ? (
                    <div className="wpuf-cover-photo__loading">
                        <span>{__('Loading...', 'wpuf-pro')}</span>
                    </div>
                ) : coverPhotoUrl ? (
                    <img
                        src={coverPhotoUrl}
                        alt={coverPhotoData?.alt || `${user.display_name} ${__('Cover Photo', 'wpuf-pro')}`}
                        className="wpuf-cover-photo__image"
                        style={{
                            width: '100%',
                            height: '100%'
                        }}
                    />
                ) : (
                    renderFallback()
                )}
            </div>
        </div>
    );

    return (
        <Fragment>
            <InspectorControls>
                <PanelBody title={__('Layout', 'wpuf-pro')} initialOpen={true}>
                    {/* Cover Height - First setting as specified */}
                    <RangeControl
                        label={__('Cover Height (px)', 'wpuf-pro')}
                        value={coverHeight}
                        onChange={(value) => setAttributes({ coverHeight: value })}
                        min={150}
                        max={600}
                        step={1}
                        __next40pxDefaultSize={true}
                        __nextHasNoMarginBottom={true}
                    />

                    {/* Cover Width */}
                    <SelectControl
                        label={__('Cover Width', 'wpuf-pro')}
                        value={coverWidth}
                        options={[
                            { label: __('Full Width', 'wpuf-pro'), value: 'full-width' },
                            { label: __('Custom', 'wpuf-pro'), value: 'custom' }
                        ]}
                        onChange={(value) => setAttributes({ coverWidth: value })}
                        __next40pxDefaultSize={true}
                        __nextHasNoMarginBottom={true}
                    />

                    {coverWidth === 'custom' && (
                        <>
                            <div>
                                <div style={{ marginBottom: '8px' }}>
                                    <label>{__('Custom Width', 'wpuf-pro')}</label>
                                </div>
                                <div className="wpuf-flex" style={{ alignItems: 'center', gap: '5%' }}>
                                    <div style={{ width: '75%', flexShrink: 0 }}>
                                        {customWidthUnit === 'px' ? (
                                            <RangeControl
                                                value={customWidthValue || 800}
                                                onChange={(value) => setAttributes({ customWidthValue: value })}
                                                min={200}
                                                max={2000}
                                                step={10}
                                                __next40pxDefaultSize={true}
                                                __nextHasNoMarginBottom={true}
                                            />
                                        ) : (
                                            <RangeControl
                                                value={customWidthValue || 100}
                                                onChange={(value) => setAttributes({ customWidthValue: value })}
                                                min={10}
                                                max={100}
                                                step={1}
                                                __next40pxDefaultSize={true}
                                                __nextHasNoMarginBottom={true}
                                            />
                                        )}
                                    </div>
                                    <div style={{ width: '25%', display: 'flex' }}>
                                        <Button
                                            isPressed={customWidthUnit === 'px'}
                                            onClick={() => setAttributes({ customWidthUnit: 'px' })}
                                            variant="secondary"
                                            size="small"
                                        >
                                            px
                                        </Button>
                                        <Button
                                            isPressed={customWidthUnit === '%'}
                                            onClick={() => setAttributes({ customWidthUnit: '%' })}
                                            variant="secondary"
                                            size="small"
                                        >
                                            %
                                        </Button>
                                    </div>
                                </div>
                            </div>
                        </>
                    )}

                    {/* Fit Type */}
                    <SelectControl
                        label={__('Fit Type', 'wpuf-pro')}
                        value={fitType}
                        options={[
                            { label: __('Cover (fill area)', 'wpuf-pro'), value: 'cover' },
                            { label: __('Contain (show whole image)', 'wpuf-pro'), value: 'contain' }
                        ]}
                        onChange={(value) => setAttributes({ fitType: value })}
                        help={__('Adjust how the image scales to fit.', 'wpuf-pro')}
                        __next40pxDefaultSize={true}
                        __nextHasNoMarginBottom={true}
                    />
                </PanelBody>
            </InspectorControls>

            <div {...blockProps}>
                {coverPhotoContent}
            </div>
        </Fragment>
    );
};

export default Edit;
