import type { Message } from '@/lib/types';
import { useEffect, useRef } from 'react';
import { ChatHeader } from './chat-header';
import { MessageBubble } from './message-bubble';
import { MessageInput } from './message-input';

interface ChatAreaProps {
    chatName: string;
    chatAvatar?: string;
    memberCount?: number;
    onlineCount?: number;
    messages: Message[];
    onSendMessage?: (message: string) => void;
    onFileSend?: (files: File[]) => void;
    onBack?: () => void;
    onInfoClick?: () => void;
}

export function ChatArea({
    chatName,
    chatAvatar,
    memberCount,
    onlineCount,
    messages,
    onSendMessage,
    onFileSend,
    onBack,
    onInfoClick,
}: ChatAreaProps) {
    const messagesEndRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    }, [messages]);

    return (
        <div className="flex h-full flex-1 flex-col bg-background">
            <ChatHeader
                name={chatName}
                avatar={chatAvatar}
                memberCount={memberCount}
                onlineCount={onlineCount}
                onBack={onBack}
                onInfoClick={onInfoClick}
            />

            <div className="no-scrollbar flex-1 overflow-y-auto p-4 md:p-6">
                <div className="mb-6 flex justify-center">
                    <span className="rounded-full bg-muted px-3 py-1 text-xs text-muted-foreground">Today</span>
                </div>

                {messages.map((message, index) => {
                    const isOwn = message.senderId === 'current';
                    const prevMessage = messages[index - 1];
                    const showAvatar = !prevMessage || prevMessage.senderId !== message.senderId;

                    return <MessageBubble key={message.id} message={message} isOwn={isOwn} showAvatar={showAvatar} />;
                })}
                <div ref={messagesEndRef} />
            </div>

            <MessageInput onSend={onSendMessage} onFileSend={onFileSend} />
        </div>
    );
}
