'use client';

import React, { useEffect, useRef } from 'react';
import { Loader2, Copy } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { Message, renderFormattedMessage } from '../../utils/chatUtils';

interface ChatDisplayProps {
    messages: Message[];
    isLoading: boolean;
}

export const ChatDisplay = ({ messages, isLoading }: ChatDisplayProps) => {
    const scrollRef = useRef<HTMLDivElement>(null);
    const [copiedIndex, setCopiedIndex] = React.useState<number | null>(null);

    // Auto-scroll to bottom when messages change
    useEffect(() => {
        if (scrollRef.current) {
            scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
        }
    }, [messages, isLoading]);

    const handleCopy = (text: string, index: number) => {
        navigator.clipboard.writeText(text).then(() => {
            setCopiedIndex(index);
            setTimeout(() => setCopiedIndex(null), 2000);
        });
    };

    if (messages.length === 0 && !isLoading) return null;

    return (
        <motion.div
            initial={{ opacity: 0, y: 10, scale: 0.95 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={{ opacity: 0, y: 10, scale: 0.95 }}
            className="absolute bottom-full left-0 w-full mb-3 max-h-[400px] overflow-y-auto custom-scrollbar p-4 flex flex-col gap-4 pointer-events-auto"
            ref={scrollRef}
        >
            {messages.map((m, i) => {
                if (m.role === 'model' && !m.text) return null;
                
                return (
                    <div key={i} className={`flex w-full ${m.role === 'user' ? 'justify-end' : 'justify-start'}`}>
                        <div className={`flex flex-col max-w-[90%] gap-1 ${m.role === 'user' ? 'items-end' : 'items-start'}`}>
                            {m.role === 'model' && (
                                <div className="flex items-center gap-1.5 px-1 mb-0.5">
                                    <span className="w-1 h-1 rounded-full bg-cyan-500/80"></span>
                                    <span className="text-[9px] font-bold text-muted-foreground uppercase tracking-wider">AI Assistant</span>
                                </div>
                            )}

                            <div className="group relative transition-all w-full">
                                <div 
                                    className={`
                                        relative px-4 py-3 rounded-2xl shadow-sm border select-text cursor-text text-xs leading-relaxed
                                        ${m.role === 'user' 
                                            ? 'bg-white/10 border-white/10 text-foreground rounded-tr-sm ml-4' 
                                            : 'bg-black/40 border-white/5 text-muted-foreground rounded-tl-sm w-full pr-8'
                                        }
                                    `}
                                >
                                    {m.role === 'model' ? renderFormattedMessage(m.text) : <p className="whitespace-pre-wrap">{m.text}</p>}
                                    
                                    {/* Copy Button */}
                                    <button 
                                        onClick={() => handleCopy(m.text, i)}
                                        className={`absolute top-2 right-2 p-1 rounded-full bg-black/50 hover:bg-black/80 border border-white/10 text-muted-foreground opacity-0 group-hover:opacity-100 transition-all z-10`}
                                        title="复制"
                                    >
                                        {copiedIndex === i ? <span className="text-[9px] font-bold text-green-500">✓</span> : <Copy size={10} />}
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                );
            })}

            {isLoading && (
                 <div className="flex justify-start w-full animate-in fade-in slide-in-from-bottom-2">
                    <div className="flex flex-col gap-2 max-w-[85%]">
                        <span className="text-[10px] font-bold uppercase tracking-wider px-1 text-cyan-500/80">Thinking</span>
                        <div className="px-5 py-3 bg-black/40 border border-white/5 rounded-2xl rounded-tl-sm flex items-center gap-3 w-fit">
                            <Loader2 size={14} className="animate-spin text-cyan-500" />
                            <span className="text-xs font-medium tracking-wide text-muted-foreground">正在思考...</span>
                        </div>
                    </div>
                </div>
            )}
        </motion.div>
    );
};
