'use client';

import { type Message } from 'ai';
import { useEffect, useState } from 'react';

import { Separator } from '@/components/ui/separator';
import { ChatMessage } from '@/components/chat-message';

export interface ChatList {
	messages: Message[];
	isLoading: boolean;
}

export function ChatList({ messages, isLoading }: ChatList) {
	const [loadingDots, setLoadingDots] = useState('');

	useEffect(() => {
		let loadingInterval: NodeJS.Timeout;

		if (isLoading) {
			loadingInterval = setInterval(() => {
				setLoadingDots(prevMessage => {
					switch (prevMessage) {
						case '':
							return '.';
						case '.':
							return '..';
						case '..':
							return '...';
						case '...':
							return '';
						default:
							return '';
					}
				});
			}, 500);
		}

		return () => {
			clearInterval(loadingInterval);
		};
	}, [isLoading]);

	if (!messages.length) {
		return null;
	}

	const assistantLoadingMessage: Message = {
		id: 'loading',
		content: loadingDots,
		role: 'assistant',
	};

	const messageWithLoading =
		isLoading && messages[messages.length - 1].role !== 'assistant'
			? [...messages, assistantLoadingMessage]
			: messages;

	return (
		<div className="relative mx-auto max-w-2xl px-8 pr-12">
			{messageWithLoading.map((message, index) => (
				<div key={index}>
					<ChatMessage message={message} />
					{index < messageWithLoading.length - 1 && (
						<Separator className="my-4 md:my-8" />
					)}
				</div>
			))}
		</div>
	);
}
