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

function FeaturedImageTab({postData, nonce, setOverlayLoading, currentStyle, currentAspect, apiKey}) {
    const {status, generatedImage, error, startGeneration} = usePixaliaGenerator();

    // Gutenbergのストアから最新のタイトルと本文を取得
    const {editedTitle, editedContent} = useSelect((select) => {
        const editor = select('core/editor');
        return {
            editedTitle: editor.getEditedPostAttribute('title'),
            editedContent: editor.getEditedPostAttribute('content'),
        };
    }, []);

    const [isSaving, setIsSaving] = useState(false);

    // 生成中のオーバーレイ同期
    useEffect(() => {
        setOverlayLoading(status === 'generating' || status === 'polling' || isSaving);
    }, [status, isSaving, setOverlayLoading]);

    // 生成実行
    const handleGenerate = () => {
        const postId = postData.id || postData.postId;

        if (!postId) {
            alert('Post ID not found.');
            return;
        }

        // タイトルが空の場合は警告
        if (!editedTitle) {
            alert(__('Please enter a title for the post first.', appConst.i18nDomain));
            return;
        }

        // ★ コンテンツの整形: HTMLタグ除去 & 5000文字制限
        let cleanContent = editedContent || '';
        cleanContent = cleanContent.replace(/<[^>]+>/g, ''); // タグ除去
        if (cleanContent.length > 5000) {
            cleanContent = cleanContent.substring(0, 5000);
        }

        startGeneration({
            title: editedTitle,     // ★ 編集中のタイトルを直接使用
            content: cleanContent, // 最新の本文
            style: currentStyle,
            aspect_ratio: currentAspect,
            target_type: 'featured',
        }, nonce);
    };

    // 保存実行
    const handleSetFeatured = async () => {
        if (!generatedImage) return;
        setIsSaving(true);
        try {
            const postId = postData.id || postData.postId;
            await attachImageToPost(postId, generatedImage, nonce, true);
            alert(__('Featured image updated successfully!', appConst.i18nDomain));
            window.location.reload();
        } catch (e) {
            alert('Error: ' + e.message);
        } finally {
            setIsSaving(false);
        }
    };


    return (
        <div className="space-y-4">
            {error && <div className="p-3 text-red-600 bg-red-50 border border-red-200 rounded text-sm">{error}</div>}

            {status === 'completed' && generatedImage ? (
                /* --- 生成完了後の表示 --- */
                <div className="animate-fade-in border rounded-lg p-3 bg-gray-50">
                    <img src={generatedImage} alt="Generated" className="w-full h-auto rounded border mb-3 shadow-sm"/>
                    <Button onClick={handleSetFeatured} className="w-full justify-center mb-2">
                        {__('Set as Featured Image', appConst.i18nDomain)}
                    </Button>
                    <button
                        onClick={() => window.location.reload()}
                        className="text-xs text-gray-500 w-full text-center hover:underline py-2"
                    >
                        {__('Discard and Try Again', appConst.i18nDomain)}
                    </button>
                </div>
            ) : (
                /* --- 生成前の表示 (シンプル化) --- */
                <div className="space-y-4 pt-2">
                    <div className="flex">
                        <Button
                            onClick={handleGenerate}
                            className="w-full justify-center py-2.5 text-base"
                            disabled={!editedTitle} // タイトルがない場合は押せないようにする
                        >
                            {__('Generate Image', appConst.i18nDomain)}
                        </Button>
                    </div>
                    {/* プロンプト入力欄を削除し、対象タイトルを表示するのみに変更 */}
                    <div className="text-sm text-gray-800">
                        {__('The AI will generate an image based on the post title and content.', appConst.i18nDomain)}
                    </div>
                </div>
            )}
        </div>
    );
}

export default FeaturedImageTab;