import React, {useState, useEffect} from 'react';
import {__} from '@wordpress/i18n';
import {useSelect, useDispatch} from '@wordpress/data';
import {createBlock} from '@wordpress/blocks';
import Button from '../atoms/Button';
import appConst from '../../apps/appConst';
import {usePixaliaGenerator} from '../../apps/hooks/usePixaliaGenerator';
import {attachImageToPost} from '../../api/client';

function SectionImageTab({postData, nonce, distUrl, currentStyle, currentAspect}) {
    const blocks = useSelect((select) => select('core/block-editor').getBlocks(), []);
    const [sections, setSections] = useState([]);

    // ★ Assets.php の 'distUrl' を使う
    // distUrl は '.../dist/' なので、そこに 'images/loading.svg' を足す
    const loadingImageUrl = distUrl ? `${distUrl}images/loading.svg` : '';

    // ブロック解析 (変更なし)
    // ブロック解析 (Hタグ〜次のHタグ直前までを収集するロジックに変更)
    const scanSections = () => {
        const detected = [];

        // ループ処理
        for (let i = 0; i < blocks.length; i++) {
            const block = blocks[i];

            // 見出しブロックを見つけたら処理開始
            if (block.name === 'core/heading') {
                const headingText = block.attributes.content;
                let contextText = '';

                // 次のブロックからループして、次の見出しが来るまでテキストを集める
                for (let j = i + 1; j < blocks.length; j++) {
                    const nextBlock = blocks[j];

                    // 次のHタグが来たら、このセクションの収集は終了
                    if (nextBlock.name === 'core/heading') {
                        break;
                    }

                    // テキストを含んでいそうなブロックから文字を抽出
                    // (パラグラフ、リスト、引用などを対象にする)
                    if (nextBlock.name === 'core/paragraph') {
                        contextText += nextBlock.attributes.content + ' ';
                    } else if (nextBlock.name === 'core/list') {
                        // リストの場合、HTMLが含まれるが、後で正規表現で消すので結合してOK
                        // (Gutenbergのバージョンによっては values 属性などの場合もあるが、通常 content/values を見る)
                        // ここでは簡易的に innerHTML 相当のものが取れると仮定、または values を解析
                        // ※ リストの扱いは複雑なので、一旦単純な content がある前提か、無視するか
                        // 簡易実装として paragraph と quote に絞るのが安全かもしれません
                    } else if (nextBlock.name === 'core/quote') {
                        contextText += nextBlock.attributes.value || nextBlock.attributes.content + ' ';
                    }
                }

                // コンテキストが長すぎる場合のカット処理 (例: 800文字)
                // タグ除去後の文字数で判定するのがベストですが、ここでは簡易的に
                if (contextText.length > 5000) {
                    contextText = contextText.substring(0, 5000) + '...';
                }

                detected.push({
                    clientId: block.clientId,
                    heading: headingText,
                    context: contextText.trim(),
                });
            }
        }

        setSections(detected);
    };

    useEffect(() => {
        scanSections();
    }, [blocks]);

    return (
        <div className="space-y-4 px-1">
            <div className="flex justify-between items-center mb-2 pb-2 border-b">
                <h3 className="text-xs font-bold text-gray-500 uppercase">{__('Detected Sections', appConst.i18nDomain)}</h3>
                <button onClick={scanSections} className="text-xs text-blue-500 hover:underline">
                    {__('Rescan', appConst.i18nDomain)}
                </button>
            </div>

            {sections.length === 0 ? (
                <div className="p-6 text-center text-gray-400 text-sm bg-gray-50 border border-dashed rounded">
                    {__('No headings (H2, H3) found.', appConst.i18nDomain)}
                </div>
            ) : (
                <ul className="space-y-3">
                    {sections.map((section) => (
                        <SectionItem
                            key={section.clientId}
                            section={section}
                            nonce={nonce}
                            postData={postData}
                            currentStyle={currentStyle}
                            currentAspect={currentAspect}
                            loadingImageUrl={loadingImageUrl} // パスを渡す
                        />
                    ))}
                </ul>
            )}
        </div>
    );
}

// 子コンポーネント (SectionItem)
function SectionItem({section, nonce, postData, currentStyle, currentAspect, loadingImageUrl}) {
    const {status, generatedImage, error, startGeneration} = usePixaliaGenerator();
    const {insertBlocks, updateBlockAttributes} = useDispatch('core/block-editor');
    const {lockPostSaving, unlockPostSaving} = useDispatch('core/editor');

    const [placeholderClientId, setPlaceholderClientId] = useState(null);

    // 完了時の処理
    useEffect(() => {
        const finalizeImage = async () => {
            if (status === 'completed' && generatedImage && placeholderClientId) {
                try {
                    const postId = postData.id || postData.postId;
                    // WPに保存
                    const uploaded = await attachImageToPost(postId, generatedImage, nonce);

                    // ブロックの画像を生成されたものに差し替え
                    updateBlockAttributes(placeholderClientId, {
                        url: uploaded.url,
                        id: uploaded.attachment_id,
                        alt: section.heading.replace(/<[^>]+>/g, ''),
                    });
                } catch (e) {
                    alert('Upload failed: ' + e.message);
                } finally {
                    unlockPostSaving('pixalia-gen');
                }
            } else if (status === 'error') {
                alert('Generation Failed: ' + error);
                unlockPostSaving('pixalia-gen');
            }
        };

        if (status === 'completed' || status === 'error') {
            finalizeImage();
        }
    }, [status, generatedImage, placeholderClientId]);

    const handleStart = () => {
        lockPostSaving('pixalia-gen');

        // ローディング画像のブロック挿入
        const placeholder = createBlock('core/image', {
            url: loadingImageUrl, // 正しいパスを使用
            alt: 'Generating...',
            caption: 'Generating by Pixalia...'
        });

        const allBlocks = wp.data.select('core/block-editor').getBlocks();
        const index = allBlocks.findIndex(b => b.clientId === section.clientId);

        if (index !== -1) {
            insertBlocks(placeholder, index + 1);

            // 挿入されたブロックを探す (簡易的)
            setTimeout(() => {
                const newBlocks = wp.data.select('core/block-editor').getBlocks();
                const inserted = newBlocks.find((b, i) => i > 0 && newBlocks[i - 1].clientId === section.clientId);
                if (inserted) {
                    setPlaceholderClientId(inserted.clientId);
                }
            }, 50);

            // API生成開始
            startGeneration({
                title: section.heading.replace(/<[^>]+>/g, ''),
                content: section.context.replace(/<[^>]+>/g, ''),
                style: currentStyle,
                aspect_ratio: currentAspect,
                target_type: 'section'
            }, nonce);
        }
    };

    const isProcessing = status === 'generating' || status === 'polling';
    const isDone = status === 'completed';

    return (
        <li className={`bg-white border rounded p-3 text-sm shadow-sm transition-colors ${isProcessing ? 'bg-blue-50' : ''}`}>
            <div className="font-bold text-gray-800 mb-1 truncate">
                {section.heading.replace(/<[^>]+>/g, '') || '(No Text)'}
            </div>

            <div className="flex justify-end">
                <Button onClick={handleStart} disabled={isProcessing} className="text-xs py-1 px-3 h-auto">
                    {isProcessing ? 'Generating...' : 'Generate & Insert'}
                </Button>
            </div>
        </li>
    );
}

export default SectionImageTab;