import type { UiMessage } from '@/contexts';
import { MessageList } from '@/components/ui/message-list';
import { MessageInput } from '@/components/ui/message-input';
import { convertMessagesToShadcn } from './chatbotKitAdapter';
import { memo, useRef } from 'react';
import { cn } from '@/lib/utils';

interface RoomChatInterfaceProps {
  messages: UiMessage[];
  input: string;
  onInputChange: (e: React.ChangeEvent<HTMLTextAreaElement>) => void;
  onSubmit: (e: React.FormEvent) => void;
  isGenerating?: boolean;
  className?: string;
}

export const RoomChatInterface = memo(function RoomChatInterface({
  messages,
  input,
  onInputChange,
  onSubmit,
  isGenerating = false,
  className,
}: RoomChatInterfaceProps) {
  const messagesEndRef = useRef<HTMLDivElement>(null);

  const shadcnMessages = convertMessagesToShadcn(messages);

  const lastMessage = messages[messages.length - 1];
  const isTyping = lastMessage?.sender_type === 'user' && isGenerating;

  return (
    <div className={cn('flex h-full flex-col', className)}>
      <div className="flex-1 overflow-y-auto px-4 py-4">
        {messages.length === 0 ? (
          <div className="flex h-full items-center justify-center">
            <div className="rounded-lg border border-dashed border-border/70 bg-muted/20 px-6 py-8 text-center">
              <p className="text-sm font-medium text-foreground">No messages yet</p>
              <p className="mt-1 text-xs text-muted-foreground">Start a conversation below</p>
            </div>
          </div>
        ) : (
          <MessageList
            messages={shadcnMessages}
            showTimeStamps={true}
            isTyping={isTyping}
          />
        )}
        <div ref={messagesEndRef} />
      </div>

      <div className="border-t border-border bg-background p-4">
        <form onSubmit={onSubmit}>
          <MessageInput
            value={input}
            onChange={onInputChange}
            placeholder="Type a message..."
            isGenerating={isGenerating}
            allowAttachments={false}
          />
        </form>
      </div>
    </div>
  );
});
