'use client';

import React, { useCallback, useEffect, useState } from 'react';
import { useDebounce } from '@/lib/hooks/useDebounce';
import { AppNodeData } from '../../types/node';

const PROMPT_DEBOUNCE_MS = 500;

interface PromptInputRendererProps {
    data: AppNodeData;
    update: (data: Partial<AppNodeData>) => void;
}

export const PromptInputRenderer = ({ data, update }: PromptInputRendererProps) => {
    const dataPrompt = data.prompt ?? '';
    const [localPrompt, setLocalPrompt] = useState(dataPrompt);
    const debouncedPrompt = useDebounce(localPrompt, PROMPT_DEBOUNCE_MS);

    // 外部数据变化时同步到本地（如加载、撤销等）
    useEffect(() => {
        setLocalPrompt(dataPrompt);
    }, [dataPrompt]);

    // 防抖后与当前节点数据不一致时才写回，减少画布刷新/保存
    useEffect(() => {
        if (debouncedPrompt !== dataPrompt) {
            update({ prompt: debouncedPrompt });
        }
    }, [debouncedPrompt, dataPrompt, update]);

    const handleChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {
        setLocalPrompt(e.target.value);
    }, []);

    return (
        <div className="w-full h-full p-6 flex flex-col group/text">
            <div className="flex-1 min-h-0 bg-black/10 rounded-2xl p-4 relative overflow-hidden backdrop-blur-sm transition-colors group-hover/text:bg-black/20">
                <textarea
                    data-testid="prompt-input-textarea"
                    className="nodrag nopan w-full h-full min-h-[60px] text-sm text-foreground/90 font-medium leading-relaxed custom-scrollbar overflow-y-auto whitespace-pre-wrap break-words bg-transparent border-none outline-none resize-none placeholder:text-slate-500 placeholder:italic"
                    value={localPrompt}
                    onChange={handleChange}
                    placeholder="请输入提示词..."
                    spellCheck={false}
                />
            </div>
        </div>
    );
};
