import React, {useEffect, useState} from 'react';
import {__} from '@wordpress/i18n';
import ImageCheckResults from '../../components/organisms/ImageCheckResults';
import Spinner from '../../components/atoms/Spinner';
import appUtil from "../appUtil";
import xIcon from '../../../images/icon/x-icon.png';
import facebookIcon from '../../../images/icon/facebook-icon.png';
import linkedinIcon from '../../../images/icon/linkedin-icon.png';
import { fetchOgpData } from '../../api/client';
import ExternalLink from '../../components/atoms/svg/ExternalLink';

const initialData = window.pixaliaPluginData || {};
const postData = initialData.postData || {};
const nonce = initialData.nonce || '';
const distUrl = initialData.distUrl || '';

/**
 * アイキャッチチェック 詳細ページ
 */
function EyecatchCheck() {
    const [ogpPreviewData, setOgpPreviewData] = useState(null);
    const [isPreviewLoading, setIsPreviewLoading] = useState(false);
    const [previewError, setPreviewError] = useState(null);
    const [ogpImageError, setOgpImageError] = useState(false); // ★ OGP画像のエラー状態

    const isPublish = initialData.postData?.status === 'publish' || false;
    const postId = postData?.postId > 0 ? postData.postId : null;


    useEffect(() => {
        // postId があり、かつ公開済みの場合のみ実行
        if (postId && isPublish && nonce) {
            setIsPreviewLoading(true);
            setPreviewError(null);
            setOgpImageError(false);

            // ★ ダミー関数ではなく、実際のAPIクライアント関数を呼び出す
            fetchOgpData(postId, nonce)
                .then(data => {
                    setOgpPreviewData(data); // 成功したらデータをセット
                })
                .catch(err => {
                    setPreviewError(err.message); // 失敗したらエラーをセット
                })
                .finally(() => {
                    setIsPreviewLoading(false); // 成功・失敗に関わらずローディング解除
                });
        }
    }, [postId, isPublish, nonce]); // 依存配列に isPublish と nonce を追加

    // ★ OGP画像のエラーをハンドリングする関数
    const handleOgpImageError = () => {
        setOgpImageError(true);
    };

    if (!postData.postId) {
        return (
            <div className="p-6">
                <h1 className="text-xl font-bold mb-4">
                    {__('Eyecatch Check', 'pixalia-image-assistant')}
                </h1>
                <div className="p-6 bg-white rounded shadow-md text-center">
                    <p className="text-lg text-gray-700">
                        {__('Click the "Image Status" of the post you want to check in the post list screen to display detailed check results and the AI image generation function.', 'pixalia-image-assistant')}
                    </p>
                    <div className="mt-6 flex flex-col items-center space-y-4">
                        <a
                            href="/wp-admin/edit.php" // 投稿一覧へのリンク
                            className="inline-block px-4 py-2 bg-blue-600 rounded hover:bg-blue-700"
                        >
                            {/* <a>タグの中はspanで囲む */}
                            <span className="text-white">
                                {__('Go to Post List', 'pixalia-image-assistant')}
                            </span>
                        </a>
                        <a
                            href={appUtil.getLpUrl()}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="text-blue-600 hover:text-blue-800 flex items-center text-base"
                        >
                            {__('Usage Guide', 'pixalia-image-assistant')}
                            <ExternalLink size={20} className="ml-1" />
                        </a>
                    </div>
                </div>
            </div>
        );
    }

    const truncatedPostTitle = appUtil.substringIfOver(postData.title, 60, true);
    const encodedPermalink = encodeURIComponent(postData.permalink);
    const twitterValidatorUrl = `https://cards-dev.twitter.com/validator?url=${encodedPermalink}`;
    const facebookDebuggerUrl = `https://developers.facebook.com/tools/debug/?q=${encodedPermalink}`;
    const linkedinValidatorUrl = `https://www.linkedin.com/post-inspector/inspect/${encodedPermalink}`;

    return (
        <div className="p-6">
            <h1 className="text-xl font-bold mb-1">
                {__('Eyecatch Check', 'pixalia-image-assistant')}
            </h1>
            {!isPublish && (
                <p className="text-yellow-600 bg-yellow-100 p-2 rounded text-sm mb-4">
                    {__('This post is not published. The preview may differ from the actual display after publication.', 'pixalia-image-assistant')}
                </p>
            )}
                <div className="text-base">ID:{postData.postId}</div>
                <div className="text-2xl mt-5 mb-6">
                    {truncatedPostTitle}
                </div>
            {/* 1. PHPによるチェック結果 */}
            <div className="p-6 bg-white rounded shadow-md mb-6">
                <ImageCheckResults results={postData.checkResults} isLoading={!postData.checkResults}/>
            </div>

            {/* 2. OGPプレビュー（汎用＋リンク） */}
            <div className="p-6 bg-white rounded shadow-md mb-6">
                <h2 className="text-lg font-semibold mb-4">{__('SNS Share Preview', 'pixalia-image-assistant')}</h2>
                {!isPublish ? (
                    <div className="p-4 text-center text-sm text-yellow-700 bg-yellow-100 rounded-md">
                        {__('This post is not published. Accurate preview is available after publication.', 'pixalia-image-assistant')}
                    </div>
                ) : isPreviewLoading ? (
                    <div className="flex flex-col items-center justify-center py-4">
                        <Spinner/>
                        <span className="ml-2">{__('Loading preview...', 'pixalia-image-assistant')}</span>
                    </div>
                ) : previewError ? (
                    <div className="p-2 text-sm text-red-700 bg-red-100 rounded-md">
                        {__('Failed to load preview:', 'pixalia-image-assistant')} {previewError}
                    </div>
                ) : ogpPreviewData ? (
                    <div>
                        {/* 汎用プレビューカード */}
                        <div className="border rounded-md overflow-hidden max-w-lg mx-auto mb-4">
                            {ogpPreviewData['og:image'] && !ogpImageError ? (
                                <img
                                    src={ogpPreviewData['og:image']}
                                    alt="OGP Preview"
                                    className="w-full block border-b"
                                    onError={handleOgpImageError}
                                />
                            ) : (
                                <div className="relative w-full max-w-lg mx-auto bg-gray-100 border-b overflow-hidden">
                                    <div style={{paddingBottom: '52.356%'}}></div>
                                    <div className="absolute inset-0 flex items-center justify-center">
							<span className="text-red-400 text-2xl p-4 text-center">
								{__('Image not available or failed to load', 'pixalia-image-assistant')}
							</span>
                                    </div>
                                </div>
                            )}
                            <div className="p-4 bg-gray-50">
                                <h3 className="font-semibold text-gray-800 text-base truncate">{ogpPreviewData['og:title']}</h3>
                                <p className="text-sm text-gray-600 mt-1 max-h-16 overflow-hidden">{ogpPreviewData['og:description']}</p>
                                <p className="text-xs text-gray-500 mt-2 uppercase">{new URL(window.location.href).hostname}</p>
                            </div>
                        </div>

                        {/* 公式ツールへのリンク */}
                        <div className="text-center mt-6">
                            <p className="text-sm font-semibold mb-3">
                                {__('Check with Official Tools:', 'pixalia-image-assistant')}
                            </p>
                            <div className="flex justify-center space-x-4">
                                <a href={twitterValidatorUrl} target="_blank" rel="noopener noreferrer" title={__('Check with X Card Validator', 'pixalia-image-assistant')}>
                                    <img src={distUrl + xIcon} alt="X Validator" className="w-6 h-6 hover:opacity-75"/>
                                </a>
                                <a href={facebookDebuggerUrl} target="_blank" rel="noopener noreferrer" title={__('Check with Facebook Debugger', 'pixalia-image-assistant')}>
                                    <img src={distUrl + facebookIcon} alt="Facebook Debugger" className="w-6 h-6 hover:opacity-75"/>
                                </a>
                                <a href={linkedinValidatorUrl} target="_blank" rel="noopener noreferrer" title={__('Check with LinkedIn Debugger', 'pixalia-image-assistant')}>
                                    <img src={distUrl + linkedinIcon} alt="LinkedIn Debugger" className="w-6 h-6 hover:opacity-75"/>
                                </a>
                            </div>
                        </div>
                    </div>
                ) : null /* OGPデータがない場合は何も表示しない */}
            </div>
        </div>
    );
}

export default EyecatchCheck;

