import React, { useState } from 'react';
import { __ } from '@wordpress/i18n';
import appConst, { imageStylesBusiness, imageStylesCreative } from '../../apps/appConst';
import FeaturedImageTab from '../../components/organisms/FeaturedImageTab';
import SectionImageTab from '../../components/organisms/SectionImageTab';
import Spinner from '../../components/atoms/Spinner';
import Button from "../../components/atoms/Button";
import Sparkles from "../../components/atoms/svg/Sparkles";
import Gift from "../../components/atoms/svg/Gift";
import ExternalLink from "../../components/atoms/svg/ExternalLink";
import SettingSvg from "../../components/atoms/svg/SettingSvg";

const initialData = window.pixaliaPluginData || {};

function PostEdit() {
    const [activeTab, setActiveTab] = useState('featured'); // 'featured' | 'section'
    const [isOverlayLoading, setIsOverlayLoading] = useState(false);

    const [globalStyle, setGlobalStyle] = useState(initialData.defaultStyle || 'photorealistic');
    const [globalAspect, setGlobalAspect] = useState(initialData.defaultAspectRatio || '16:9');

    // 外部リンク用のハンドラ
    const openSettings = (e) => {
        e.preventDefault();
        window.open('admin.php?page=pixalia-settings', '_blank');
    };

    const openRegister = (e) => {
        e.preventDefault();
        window.open('https://pixalia.me/', '_blank');
    };

    // データがない場合のガード (新規投稿の直後など)
    if (!initialData.postData) {
        return <div className="p-4 text-sm text-gray-500 bg-gray-50 border rounded">{__('Please save the post first to use Pixalia.', appConst.i18nDomain)}</div>;
    }
     if (!initialData.apiKey || initialData.apiKey === '') {
        return (
            <div className="font-sans text-gray-800">
                <div className="flex flex-col items-center text-center space-y-4 py-4">
                    {/* アイコン */}
                    <div className="bg-blue-50 p-3 rounded-full mb-1">
                        <Sparkles size={24} className="text-blue-600" />
                    </div>

                    {/* 説明文 */}
                    <div className="space-y-2 px-1">
                        <h3 className="text-sm font-bold text-gray-800">
                            {__('Setup Required', appConst.i18nDomain)}
                        </h3>
                        <p className="text-xs text-gray-500 leading-relaxed">
                            {__('To start generating featured images, please configure your API Key.', appConst.i18nDomain)}
                        </p>
                    </div>

                    {/* アクションボタン */}
                    <div className="w-full space-y-4 mt-2">
                        {/* 設定画面へ */}
                        <Button onClick={openSettings} className="w-full py-2 shadow-sm text-xs justify-center">
                            <SettingSvg size={14} className="mr-2" />
                            {__('Enter API Key', appConst.i18nDomain)}
                        </Button>

                        {/* 区切り線 */}
                        <div className="relative py-1">
                            <div className="absolute inset-0 flex items-center">
                                <span className="w-full border-t border-gray-100" />
                            </div>
                            <div className="relative flex justify-center text-[10px] uppercase">
                                <span className="bg-white px-2 text-gray-400">or</span>
                            </div>
                        </div>

                        {/* 無料登録案内 */}
                        <div>
                            <p className="text-[10px] text-gray-400 mb-1.5">
                                {__("Don't have an account?", appConst.i18nDomain)}
                            </p>
                            <button
                                onClick={openRegister}
                                className="flex items-center justify-center gap-1.5 w-full py-2 border border-blue-100 bg-white rounded text-xs font-medium text-blue-600 hover:bg-blue-50 transition-colors"
                            >
                                <Gift size={14} className="text-pink-500" />
                                {__('Get 200 Free Credits', appConst.i18nDomain)}
                                <a> </a>
                                <ExternalLink size={10} className="text-blue-400 ml-0.5" />
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        );
    }
    return (
        <div className="pixalia-meta-box relative bg-white">

            {/* --- 全画面オーバーレイ (アイキャッチ生成中のみ) --- */}
            {isOverlayLoading && (
                <div className="fixed inset-0 z-[9999] bg-black/70 flex flex-col items-center justify-center backdrop-blur-sm text-white">
                    <div className="bg-white p-6 rounded-lg shadow-xl flex flex-col items-center">
                        <Spinner /> {/* AtomsのSpinnerは色調整が必要かも。ここではSVG直書きかCSS調整推奨 */}
                        <p className="text-gray-800 text-lg font-bold mt-4 animate-pulse">{__('Generating Featured Image...', appConst.i18nDomain)}</p>
                        <p className="text-gray-500 text-sm mt-2">{__('Please do not close this page.', appConst.i18nDomain)}</p>
                    </div>
                </div>
            )}
            {/* --- 共通設定エリア (Style / Ratio) --- */}
            <div className="p-3 bg-gray-50 border-b border-gray-200 space-y-2 mb-0">
                <div className="">
                    <div className="mb-2">
                        <label className="block text-xs font-bold text-gray-500 uppercase mb-1">
                            {__('Style', appConst.i18nDomain)}
                        </label>
                        <select
                            value={globalStyle}
                            onChange={(e) => setGlobalStyle(e.target.value)}
                            className="w-full text-xs py-1 px-2 border-gray-300 rounded focus:ring-blue-500 focus:border-blue-500"
                        >
                            {/* ★ カテゴリごとにグループ化して表示 */}
                            <optgroup label="Business">
                                {imageStylesBusiness.map(opt => (
                                    <option key={opt.value} value={opt.value}>{opt.label}</option>
                                ))}
                            </optgroup>
                            <optgroup label="Creative">
                                {imageStylesCreative.map(opt => (
                                    <option key={opt.value} value={opt.value}>{opt.label}</option>
                                ))}
                            </optgroup>
                        </select>
                    </div>
                    <div className="mt-2">
                        <label className="block text-xs font-bold text-gray-500 uppercase mb-1">
                            {__('Ratio', appConst.i18nDomain)}
                        </label>
                        <select
                            value={globalAspect}
                            onChange={(e) => setGlobalAspect(e.target.value)}
                            className="w-full text-xs py-1 px-2 border-gray-300 rounded focus:ring-blue-500 focus:border-blue-500"
                        >
                            <option value="1">16:9</option>
                            <option value="2">1:1</option>
                            <option value="3">9:16</option>
                        </select>
                    </div>
                </div>
            </div>

            {/* --- タブ切り替え --- */}
            <div className="flex border-b border-gray-200 my-4">
                <button
                    className={`flex-1 py-2 text-sm font-medium transition-colors ${activeTab === 'featured' ? 'text-blue-600 border-b-2 border-blue-600 bg-blue-50' : 'text-gray-500 hover:text-gray-700 hover:bg-gray-50'}`}
                    onClick={() => setActiveTab('featured')}
                >
                    {__('Featured Image', appConst.i18nDomain)}
                </button>
                <button
                    className={`flex-1 py-2 text-sm font-medium transition-colors ${activeTab === 'section' ? 'text-blue-600 border-b-2 border-blue-600 bg-blue-50' : 'text-gray-500 hover:text-gray-700 hover:bg-gray-50'}`}
                    onClick={() => setActiveTab('section')}
                >
                    {__('Section Images', appConst.i18nDomain)}
                </button>
            </div>

            {/* --- コンテンツエリア --- */}
            <div className="min-h-[300px]">
                {activeTab === 'featured' && (
                    <FeaturedImageTab
                        postData={initialData.postData}
                        nonce={initialData.nonce}
                        setOverlayLoading={setIsOverlayLoading}
                        currentStyle={globalStyle}
                        currentAspect={globalAspect}
                        apiKey={''}
                    />
                )}
                {activeTab === 'section' && (
                    <SectionImageTab
                        postData={initialData.postData}
                        nonce={initialData.nonce}
                        distUrl={initialData.distUrl}
                        currentStyle={globalStyle}
                        currentAspect={globalAspect}
                    />
                )}
            </div>
        </div>
    );
}

export default PostEdit;