/**
 * WordPress dependencies
 */
import { useState, useRef } from '@wordpress/element';
import {
    TextareaControl,
    TextControl,
    SelectControl,
    Button,
    Spinner,
    Placeholder,
    Notice,
    ToggleControl,
} from '@wordpress/components';
import { useBlockProps } from '@wordpress/block-editor';
import { useSelect } from '@wordpress/data';
import { __ } from '@wordpress/i18n';
import apiFetch from '@wordpress/api-fetch';

/**
 * Edit component for the AI Image Generator block.
 *
 * @param {Object} props               Block props.
 * @param {Object} props.attributes    Block attributes.
 * @param {Function} props.setAttributes Function to update attributes.
 * @return {JSX.Element} Block editor component.
 */
export default function Edit({ attributes, setAttributes }) {
    const { prompt, useCustomSettings, style, aspectRatio, imageUrl, attachmentId, alt, customText } = attributes;
    const [isGenerating, setIsGenerating] = useState(false);
    const [error, setError] = useState(null);
    const blockRef = useRef(null);

    const blockProps = useBlockProps({ ref: blockRef });
    const enabledPostTypes = window.aifiBlockData?.enabledPostTypes || ['post', 'page'];

    // Get the current post type from the editor
    const currentPostType = useSelect(
        (select) => select('core/editor')?.getCurrentPostType?.() || 'post',
        []
    );

    // Check if the current post type is enabled for inline image generation
    const isPostTypeEnabled = enabledPostTypes.includes(currentPostType);

    // Get global defaults from settings
    const globalStyle = window.aifiBlockData?.defaultStyle || 'realistic';
    const globalAspectRatio = window.aifiBlockData?.defaultAspectRatio || '16:9';

    // Effective values: use custom if enabled, otherwise use global
    const effectiveStyle = useCustomSettings ? (style || globalStyle) : globalStyle;
    const effectiveAspectRatio = useCustomSettings ? (aspectRatio || globalAspectRatio) : globalAspectRatio;

    // Get current provider from settings
    const currentProvider = window.aifiBlockData?.currentProvider || 'openai';

    // Note: Text on image is always enabled for blocks (independent from Featured Image setting)

    // Get style options from localized data
    const styleOptions = Object.entries(window.aifiBlockData?.styles || {}).map(([value, label]) => ({
        value,
        label,
    }));

    // Get provider-specific aspect ratio options
    const providerRatios = window.aifiBlockData?.aspectRatios?.[currentProvider] || {};
    const aspectRatioOptions = Object.entries(providerRatios).map(([value, data]) => ({
        value,
        label: `${data.label} → ${data.size}`,
    }));

    /**
     * Get the current container width for size optimization.
     *
     * @param {HTMLElement} element The block element.
     * @return {number} The container width in pixels.
     */
    const getContainerWidth = (element) => {
        if (!element) return 1200;
        const container = element.closest('.wp-block') || element;
        return container.offsetWidth || 1200;
    };

    /**
     * Handle custom settings toggle.
     * When enabling, initialize custom values from current globals.
     */
    const handleCustomSettingsToggle = (enabled) => {
        if (enabled) {
            setAttributes({
                useCustomSettings: true,
                style: globalStyle,
                aspectRatio: globalAspectRatio,
            });
        } else {
            setAttributes({ useCustomSettings: false });
        }
    };

    /**
     * Handle image generation.
     */
    const handleGenerate = async () => {
        if (!prompt.trim()) {
            setError(__('Please enter a prompt.', 'ai-featured-image-generator'));
            return;
        }

        setIsGenerating(true);
        setError(null);

        const displayWidth = getContainerWidth(blockRef.current);

        try {
            const response = await apiFetch({
                path: '/aifi/v1/generate-block-image',
                method: 'POST',
                data: {
                    prompt,
                    style: effectiveStyle,
                    aspect_ratio: effectiveAspectRatio,
                    display_width: displayWidth,
                    custom_text: customText,
                },
            });

            if (response.success) {
                setAttributes({
                    imageUrl: response.url,
                    attachmentId: response.attachmentId,
                    alt: response.alt || prompt.substring(0, 125),
                    width: response.width,
                    height: response.height,
                });
            }
        } catch (err) {
            setError(err.message || __('Failed to generate image.', 'ai-featured-image-generator'));
        } finally {
            setIsGenerating(false);
        }
    };

    /**
     * Handle regeneration.
     */
    const handleRegenerate = () => {
        setAttributes({
            imageUrl: '',
            attachmentId: 0,
            alt: '',
            width: 0,
            height: 0,
        });
    };

    /**
     * Get display label for current style.
     */
    const getStyleLabel = (styleValue) => {
        const styles = window.aifiBlockData?.styles || {};
        return styles[styleValue] || styleValue;
    };

    // Post type not enabled - show disabled state
    if (!isPostTypeEnabled) {
        return (
            <div {...blockProps}>
                <div className="aifi-block-disabled-posttype">
                    <div className="aifi-block-disabled-posttype-icon">
                        <span className="dashicons dashicons-hidden"></span>
                    </div>
                    <h4>{__('AI Image Generator', 'ai-featured-image-generator')}</h4>
                    <p>{__('This block is disabled for the current post type.', 'ai-featured-image-generator')}</p>
                    <Button
                        variant="secondary"
                        href={window.aifiBlockData?.settingsUrl || '/wp-admin/admin.php?page=ai-featured-image-generator&tab=general'}
                        target="_blank"
                        className="aifi-block-settings-btn"
                    >
                        <span className="dashicons dashicons-admin-generic"></span>
                        {__('Enable in Settings', 'ai-featured-image-generator')}
                    </Button>
                </div>
            </div>
        );
    }

    // If image exists, show it with regenerate option
    if (imageUrl) {
        const { width, height } = attributes;
        const imageBlockProps = {
            ...blockProps,
            className: `${blockProps.className || ''} aifi-block-has-image`.trim(),
        };

        return (
            <figure {...imageBlockProps}>
                <img
                    src={imageUrl}
                    alt={alt || ''}
                    width={width || undefined}
                    height={height || undefined}
                    style={{ maxWidth: '100%', height: 'auto' }}
                />
                <div className="aifi-block-toolbar">
                    <Button
                        variant="secondary"
                        onClick={handleRegenerate}
                        icon="update"
                    >
                        {__('Regenerate', 'ai-featured-image-generator')}
                    </Button>
                </div>
            </figure>
        );
    }

    // Form UI with all controls inline
    return (
        <div {...blockProps}>
            <Placeholder
                icon="format-image"
                label={__('AI Image Generator', 'ai-featured-image-generator')}
                instructions={__('Generate an AI-powered image from your prompt.', 'ai-featured-image-generator')}
                className="aifi-block-placeholder"
            >
                {error && (
                    <Notice status="error" isDismissible={false} className="aifi-block-notice">
                        {error}
                    </Notice>
                )}

                <TextareaControl
                    label={__('Image Prompt', 'ai-featured-image-generator')}
                    value={prompt}
                    onChange={(value) => setAttributes({ prompt: value })}
                    placeholder={__('Describe the image you want to generate...', 'ai-featured-image-generator')}
                    rows={3}
                    className="aifi-block-prompt"
                />

                <TextControl
                    label={__('Text on Image (optional)', 'ai-featured-image-generator')}
                    value={customText}
                    onChange={(value) => setAttributes({ customText: value })}
                    placeholder={__('Add text overlay to your image...', 'ai-featured-image-generator')}
                    help={__('Leave empty for no text overlay.', 'ai-featured-image-generator')}
                    className="aifi-block-custom-text"
                />

                <div className="aifi-block-settings-section">
                    <ToggleControl
                        label={__('Customize settings', 'ai-featured-image-generator')}
                        checked={useCustomSettings}
                        onChange={handleCustomSettingsToggle}
                        className="aifi-block-toggle"
                    />

                    {useCustomSettings ? (
                        <div className="aifi-block-row">
                            <SelectControl
                                label={__('Style', 'ai-featured-image-generator')}
                                value={style || globalStyle}
                                options={styleOptions}
                                onChange={(value) => setAttributes({ style: value })}
                            />
                            <SelectControl
                                label={__('Aspect Ratio', 'ai-featured-image-generator')}
                                value={aspectRatio || globalAspectRatio}
                                options={aspectRatioOptions}
                                onChange={(value) => setAttributes({ aspectRatio: value })}
                            />
                        </div>
                    ) : (
                        <div className="aifi-block-global-info">
                            <span className="dashicons dashicons-admin-settings"></span>
                            {__('Using global defaults:', 'ai-featured-image-generator')}
                            {' '}
                            <strong>{getStyleLabel(globalStyle)}</strong>
                            {' • '}
                            <strong>{globalAspectRatio}</strong>
                        </div>
                    )}
                </div>

                <Button
                    variant="primary"
                    onClick={handleGenerate}
                    disabled={isGenerating || !prompt.trim()}
                    className="aifi-block-generate-btn"
                >
                    {isGenerating ? (
                        <>
                            <Spinner />
                            {__('Generating...', 'ai-featured-image-generator')}
                        </>
                    ) : (
                        __('Generate Image', 'ai-featured-image-generator')
                    )}
                </Button>
            </Placeholder>
        </div>
    );
}
