import React, {useState, useEffect} from 'react';
import {__} from '@wordpress/i18n';
import {saveApiKey, fetchUncheckedCount, runBulkCheckBatch, fetchUserStatus} from '../../api/client';
import Button from '../../components/atoms/Button';
import appConst from "../appConst";
import appUtil from "../appUtil";
import Spinner from "../../components/atoms/Spinner";
import MessageModal from "../../components/organisms/MessageModal"; // Button Atomをインポート
import {imageStylesBusiness, imageStylesCreative} from "../appConst"
import ExternalLink from "../../components/atoms/svg/ExternalLink";

// PHPから渡された初期データをグローバル変数から取得
const initialData = window.pixaliaPluginData || {};
// セキュリティ用のnonce
const nonce = initialData.nonce || '';
const distUrl = initialData.distUrl || '';
// 一括チェックが必要かどうかの初期状態
const initNeedsBulkCheck = initialData.needsBulkCheck || false;
const initApiKey = initialData.apiKey || '';

const initStyle = initialData.defaultStyle || 'minimalist_flat';
const initAspect = initialData.defaultAspectRatio || '1';

/**
 * 設定ページ
 */
function Settings() {
    // --- APIキー用の State ---
    const [apiKey, setApiKey] = useState(initApiKey || '');
    const [apiSaveStatus, setApiSaveStatus] = useState(''); // 'saving', 'success', 'error'
    const [apiSaveMessage, setApiSaveMessage] = useState('');

    const [defaultStyle, setDefaultStyle] = useState(initStyle);
    const [defaultAspect, setDefaultAspect] = useState(initAspect);

    const [userData, setUserData] = useState(null);

    // --- 一括チェック用の State ---
    const [isBulkCheckLoading, setIsBulkCheckLoading] = useState(true);
    const [needsBulkCheck, setNeedsBulkCheck] = useState(initNeedsBulkCheck); // 一括チェックが必要か
    const [checkStatus, setCheckStatus] = useState('idle'); // 'idle', 'counting', 'running', 'error', 'complete'
    const [totalCount, setTotalCount] = useState(0);
    const [processedCount, setProcessedCount] = useState(0);
    const [checkError, setCheckError] = useState('');

    const [activeStyleTab, setActiveStyleTab] = useState('business');

    // モーダル表示用の State
    const [showCompleteModal, setShowCompleteModal] = useState(false);
    // モーダルを閉じるハンドラー
    const handleCloseModal = () => {
        setShowCompleteModal(false);
    };


    const bulkCheckStatusEnum = {
        IDLE: 'idle',
        COUNTING: 'counting',
        RUNNING: 'running',
        ERROR: 'error',
        COMPLETE: 'complete',
    };


// ※ window.pixaliaPluginData.pluginUrl がある前提

// 画像URL生成ヘルパー
    const getStyleImageUrl = (styleValue) => {
        // 例: wp-content/plugins/pixalia-image-assistant/assets/images/styles/photorealistic.png
        return `${distUrl}images/styles/${styleValue}.png`;
    };

    // アスペクト比の選択肢
    const aspectOptions = [
        {value: '1', label: '16:9 (Landscape)'},
        {value: '2', label: '1:1 (Square)'},
        {value: '3', label: '9:16 (Portrait)'},
    ];
    useEffect(() => {
        // APIキーがある場合のみ取得しにいく
        if (apiKey) {
            handleFetchUserStatus();
        }
    }, []); // 空配列 = マウント時1回だけ実行

    const handleFetchUserStatus = async () => {
        try {
            const data = await fetchUserStatus(nonce);
            setUserData(data);
        } catch (error) {
            console.error("Failed to fetch status:", error);
            // APIキーが無効になっている可能性もあるので、エラー時はuserDataを消すか、エラー表示するか
            setUserData(null);
        } finally {
        }
    };


    useEffect(() => {
        //一括チェックが必要場合は初期表示で一括チェック対象の総件数を取得する
        if (needsBulkCheck) {
            //総数を取得
            handleFetchUncheckedCount();
        }
    }, []);

    // 保存処理 (APIキー + デフォルト設定)
    const handleSaveSettings = async () => {
        setApiSaveStatus('saving');
        try {
            // ★ saveApiKey を拡張して、style, aspect も送れるようにclient.jsを修正する想定
            const response = await saveApiKey(apiKey, defaultStyle, defaultAspect, nonce);

            setApiSaveMessage(response.message || '保存しました。');
            setApiSaveStatus('success');

            // ★ ユーザー情報があればセット
            if (response.user_data) {
                setUserData(response.user_data);
            } else {
                setUserData(null);
            }

        } catch (error) {
            setApiSaveMessage(error.message);
            setApiSaveStatus('error');
            setUserData(null);
        }
    };

    // --- 一括チェック関連の関数 ---
    // 1. 未チェックの総件数を取得（一括チェック開始時）
    const handleFetchUncheckedCount = async () => {
        setCheckStatus(bulkCheckStatusEnum.COUNTING);
        setIsBulkCheckLoading(true);
        setCheckError('');
        try {
            const response = await fetchUncheckedCount(nonce);
            const count = response.count || 0;
            await appUtil.sleep(100);

            setTotalCount(count);
            setCheckStatus(bulkCheckStatusEnum.IDLE)
            setIsBulkCheckLoading(false);
        } catch (error) {
            setCheckStatus(bulkCheckStatusEnum.ERROR);
            setCheckError(error.message);
        }
    };

    // 2. バッチ処理の実行（AJAXチェーン）
    const handleRunBulkCheck = async () => {
        setCheckStatus(bulkCheckStatusEnum.RUNNING);
        setCheckError('');

        try {
            const response = await runBulkCheckBatch(nonce);
            const remaining = response.remaining || 0;
            const processed = totalCount - remaining; // 総数から残り件数を引いて進捗を計算
            setProcessedCount(processed);

            if (remaining > 0) {
                // まだ残りがある場合は、次のバッチ処理を（少し間を置いて）実行
                setTimeout(handleRunBulkCheck, 100); // 0.1秒待機
            } else {
                await appUtil.sleep(500); //早すぎる場合があるので少し待機
                // 完了処理
                setCheckStatus(bulkCheckStatusEnum.COUNTING);
                setNeedsBulkCheck(false);
                //ここでモーダル出す
                setShowCompleteModal(true);
            }
        } catch (error) {
            setCheckStatus(bulkCheckStatusEnum.ERROR);
            setCheckError(error.message);
        }
    };

    // --- レンダリング ---
    return (
        <div className="p-6">
            <h1 className="text-xl font-bold mb-1">{__('Settings', appConst.i18nDomain)}</h1>
            <div className="my-4">
                <a
                    href={appUtil.getLpUrl()}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-blue-600 hover:text-blue-800 flex items-center text-lg"
                >
                    {__('Usage Guide', 'pixalia-image-assistant')}
                    <ExternalLink size={22} className="ml-1" />
                </a>
            </div>
            {/* 一括チェック機能は一括チェックが必要な場合*/}
            {needsBulkCheck && (
                <div className="p-6 bg-white rounded shadow-md mb-6 border-l-8 border-amber-200">
                    <h2 className="text-xl font-semibold">{__('Existing posts need to be checked', appConst.i18nDomain)}</h2>
                    {isBulkCheckLoading && (
                        <div className="p-5">
                            <Spinner/>
                        </div>
                    )}
                    {/* アイドル時（ボタン表示） */}
                    {checkStatus === bulkCheckStatusEnum.IDLE && (
                        <div className="p-3">
                            <div className="mb-6 text-base text-gray-700">
                                {totalCount + __(' posts need to be checked. Press the button to start.', appConst.i18nDomain)}
                            </div>
                            <Button onClick={() => handleRunBulkCheck()}>
                                {__('Start Bulk Check', appConst.i18nDomain)}
                            </Button>
                        </div>
                    )}

                    {/* 総件数カウント中 */}
                    {checkStatus === bulkCheckStatusEnum.COUNTING && (
                        <p>{__('Calculating unchecked posts...', appConst.i18nDomain)}</p>
                    )}

                    {/* 処理実行中（進捗表示） */}
                    {checkStatus === bulkCheckStatusEnum.RUNNING && (
                        <div>
                            <p className="mb-2 font-semibold">
                                {__('Checking posts...', appConst.i18nDomain)}
                                ({processedCount} / {totalCount})
                            </p>
                            <div className="w-full bg-gray-200 rounded-full h-2.5">
                                <div
                                    className="bg-blue-600 h-2.5 rounded-full"
                                    style={{width: `${(processedCount / totalCount) * 100}%`}}
                                ></div>
                            </div>
                            <p className="mt-2 text-sm text-gray-500">{__('Please keep this tab open until the process is complete.', appConst.i18nDomain)}</p>
                        </div>
                    )}

                    {/* エラー時 */}
                    {checkStatus === bulkCheckStatusEnum.ERROR && (
                        <div>
                            <p className="text-red-600 mb-4">{__('An error occurred:', appConst.i18nDomain)} {checkError}</p>
                            <Button onClick={() => handleFetchUncheckedCount(true)}>
                                {__('Resume Check', appConst.i18nDomain)}
                            </Button>
                        </div>
                    )}
                </div>
            )}
            {/* すでに一括チェック済みの場合*/}
            {needsBulkCheck === false && (
                <div className="p-6 bg-white rounded shadow-md mb-6 border-l-8 border-green-200">
                    <div className="text-green-600 text-lg">{__('All posts are checked.', appConst.i18nDomain)}</div>
                    <p className="text-sm">
                        <a href="/wp-admin/edit.php" className="text-blue-600 hover:underline">
                            {__('Check the post list for details.', appConst.i18nDomain)}
                        </a>
                    </p>
                </div>
            )}


            {/* ★設定エリア */}
            <div className="bg-white rounded-lg shadow-md overflow-hidden">
                <div className="p-6 border-b border-gray-100">
                    <h2 className="text-lg font-semibold mb-4 text-gray-800">{__('General Settings', appConst.i18nDomain)}</h2>

                    {/* 接続ステータス表示 */}
                    {userData && (
                        <div className="mb-6 px-4 bg-green-50 border border-green-200 rounded-md flex items-start animate-fade-in">
                            <div className="text-sm text-green-700">
                                <p>{__('Plan:', appConst.i18nDomain)} <strong>{userData.plan_name}</strong></p>
                                <p>{__('Credits:', appConst.i18nDomain)} <strong>{userData.credits} pt</strong></p>
                            </div>
                        </div>
                    )}

                    {(!initApiKey || initApiKey === '') &&  (
                        <div>
                            <div>
                                <h3 className="text-base font-bold text-gray-900 mb-2">
                                    {__('1. Get your API Key', appConst.i18nDomain)}
                                </h3>
                                <p className="text-sm text-gray-600 mb-4 leading-relaxed">
                                    {__('Create a free account to get your API key. You will receive 200 points immediately upon registration.', appConst.i18nDomain)}
                                </p>
                                <a
                                    href="https://pixalia.me/"
                                    className="flex items-center justify-center w-64 py-2.5 bg-blue-50 text-blue-700 font-bold rounded-lg border border-blue-200 hover:bg-blue-100 transition-colors mb-2"
                                    target="_blank"
                                    rel="noopener noreferrer"
                                >
                                    {__('Get API Key (Free)', appConst.i18nDomain)}
                                    <ExternalLink size={16} className="ml-2"/>
                                </a>
                            </div>

                            <div className="border-t border-gray-100 pt-6">
                                <h3 className="text-base font-bold text-gray-900 mb-2">
                                    {__('2. Connect Plugin', appConst.i18nDomain)}
                                </h3>
                            </div>
                        </div>
                    )}
                    <div className="grid gap-6">
                        {/* API Key */}
                        <div>
                            <label htmlFor="pixalia-api-key" className="block text-sm font-medium text-gray-700 mb-1">
                                {__('Pixalia API Key', appConst.i18nDomain)}
                            </label>
                            <input
                                type="text" // セキュリティのためpassword推奨だが、確認用にtextでも可
                                id="pixalia-api-key"
                                value={apiKey}
                                onChange={(e) => setApiKey(e.target.value)}
                                className="w-full max-w-lg rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                                placeholder="pk_live_..."
                            />
                            <p className="mt-1 text-xs text-gray-500">
                                {__('Enter your Pixalia license key.', appConst.i18nDomain)}
                            </p>
                        </div>

                        <div className="mt-8">
                            <label className="block text-sm font-medium text-gray-700 mb-3">
                                {__('Default Art Style', appConst.i18nDomain)}
                            </label>

                            {/* タブ切り替え */}
                            <div className="flex space-x-1 bg-gray-100 p-1 rounded-lg w-fit mb-4">
                                <button
                                    type="button"
                                    onClick={() => setActiveStyleTab('business')}
                                    className={`px-4 py-2 text-sm font-medium rounded-md transition-colors ${
                                        activeStyleTab === 'business'
                                            ? 'bg-white text-blue-600 shadow-sm'
                                            : 'text-gray-500 hover:text-gray-700'
                                    }`}
                                >
                                    Business / Tech
                                </button>
                                <button
                                    type="button"
                                    onClick={() => setActiveStyleTab('creative')}
                                    className={`px-4 py-2 text-sm font-medium rounded-md transition-colors ${
                                        activeStyleTab === 'creative'
                                            ? 'bg-white text-purple-600 shadow-sm'
                                            : 'text-gray-500 hover:text-gray-700'
                                    }`}
                                >
                                    Creative / Art
                                </button>
                            </div>

                            {/* スタイルグリッド */}
                            <div className="min-h-[200px]">
                                <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-3">
                                    { /* アクティブなタブに応じて配列を切り替え */}
                                    {(activeStyleTab === 'business' ? imageStylesBusiness : imageStylesCreative).map((style) => {
                                        const isSelected = defaultStyle === style.value;
                                        // タブごとのテーマカラー（Business=Blue, Creative=Purple）
                                        const themeColorClass = activeStyleTab === 'business' ? 'blue' : 'purple';

                                        // ボーダー色とリング色の動的クラス
                                        const activeClasses = activeStyleTab === 'business'
                                            ? 'border-blue-600 ring-2 ring-blue-100'
                                            : 'border-purple-600 ring-2 ring-purple-100';

                                        const textActiveColor = activeStyleTab === 'business' ? 'text-blue-600' : 'text-purple-600';
                                        const bgActiveColor = activeStyleTab === 'business' ? 'bg-blue-600' : 'bg-purple-600';

                                        return (
                                            <button
                                                key={style.value}
                                                type="button"
                                                onClick={() => setDefaultStyle(style.value)}
                                                className={`
                                                group relative flex flex-col items-start p-0 border-2 rounded-xl 
                                                transition-all duration-200 overflow-hidden text-left bg-white h-full
                                                ${isSelected ? `${activeClasses} shadow-md` : 'border-transparent hover:border-gray-200 hover:shadow-sm'}
                                            `}
                                            >
                                                {/* 画像エリア (aspect-16/10 はtailwind.configの設定が必要かも。なければ style={{ aspectRatio: '16/10' }} ) */}
                                                <div className="w-full relative overflow-hidden bg-gray-100" style={{aspectRatio: '16/10'}}>
                                                    <img
                                                        src={getStyleImageUrl(style.value)}
                                                        alt={style.label}
                                                        className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105 opacity-90 group-hover:opacity-100"
                                                        // 画像がない場合のエラーハンドリング（オプション）
                                                        onError={(e) => e.target.style.display = 'none'}
                                                    />

                                                    {/* 画像がない場合のフォールバック（背景色） */}
                                                    <div className="absolute inset-0 bg-gray-200 flex items-center justify-center -z-10">
                                                        <span className="text-xs text-gray-400">No Image</span>
                                                    </div>

                                                    {/* 選択時のチェックマークオーバーレイ */}
                                                    {isSelected && (
                                                        <div
                                                            className={`absolute inset-0 ${activeStyleTab === 'business' ? 'bg-blue-600/20' : 'bg-purple-600/20'} flex items-center justify-center backdrop-blur-[1px]`}>
                                                            <div className={`${bgActiveColor} text-white rounded-full p-1.5 shadow-sm`}>
                                                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" className="w-5 h-5">
                                                                    <path fillRule="evenodd"
                                                                          d="M16.704 4.153a.75.75 0 0 1 .143 1.052l-8 10.5a.75.75 0 0 1-1.127.075l-4.5-4.5a.75.75 0 0 1 1.06-1.06l3.894 3.893 7.48-9.817a.75.75 0 0 1 1.05-.143Z"
                                                                          clipRule="evenodd"/>
                                                                </svg>
                                                            </div>
                                                        </div>
                                                    )}
                                                </div>

                                                {/* ラベルエリア */}
                                                <div className="p-2 w-full">
                                                <span className={`text-xs font-bold block leading-tight truncate ${isSelected ? textActiveColor : 'text-gray-700'}`}>
                                                    {style.label}
                                                </span>
                                                </div>
                                            </button>
                                        );
                                    })}
                                </div>
                            </div>
                        </div>

                        {/* デフォルト比率 */}
                        <div>
                            <label htmlFor="default-aspect" className="block text-sm font-medium text-gray-700 mb-1">
                                {__('Default Aspect Ratio', appConst.i18nDomain)}
                            </label>
                            <select
                                id="default-aspect"
                                value={defaultAspect}
                                onChange={(e) => setDefaultAspect(e.target.value)}
                                className="w-full max-w-xs rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                            >
                                {aspectOptions.map(opt => (
                                    <option key={opt.value} value={opt.value}>{opt.label}</option>
                                ))}
                            </select>
                        </div>
                    </div>
                </div>

                {/* フッターアクション */}
                <div className="px-6 py-4 bg-gray-50 flex items-center justify-between">
                    <Button onClick={handleSaveSettings} disabled={apiSaveStatus === 'saving'}>
                        {apiSaveStatus === 'saving' ? __('Saving...', appConst.i18nDomain) : __('Save Changes', appConst.i18nDomain)}
                    </Button>

                    {apiSaveMessage && (
                        <span className={`text-sm font-medium ${apiSaveStatus === 'error' ? 'text-red-600' : 'text-green-600'}`}>
                            {apiSaveMessage}
                        </span>
                    )}
                </div>
            </div>

            {showCompleteModal && (
                <MessageModal
                    onClose={handleCloseModal}
                    title={__('Bulk Check Complete', appConst.i18nDomain)}
                    message={
                        <>
                            <p className="mb-4">
                                {__('Successfully checked and updated', 'pixalia-image-assistant')} {totalCount} {__('posts.', 'pixalia-image-assistant')}
                            </p>
                            <p className="text-sm">
                                {__('You can now see the updated statuses in the post list.', 'pixalia-image-assistant')}
                            </p>
                        </>
                    }
                />
            )}
        </div>
    );
}

export default Settings;