'use client';

import { useChat, type Message } from 'ai/react';

import { cn } from '@/lib/utils';
import { ChatList } from '@/components/chat/ChatList';
import { ChatPanel } from '@/components/chat-panel';
import { ChatScrollAnchor } from '@/components/chat-scroll-anchor';
import { toast } from 'react-hot-toast';
import { useAtom } from 'jotai';
import { datasetAtom } from '@/state';
import ImageList from './ImageList';

export interface ChatProps extends React.ComponentProps<'div'> {
	initialMessages?: Message[];
	id?: string;
}

export function Chat({ id, initialMessages, className }: ChatProps) {
	const [dataset] = useAtom(datasetAtom);
	const { messages, append, reload, stop, isLoading, input, setInput } =
		useChat({
			initialMessages,
			id,
			body: {
				id,
				dataset: dataset,
			},
			onResponse(response) {
				if (response.status === 401) {
					toast.error(response.statusText);
				}
			},
		});

	return (
		<>
			<div className={cn('pb-[150px] pt-4 md:pt-10 h-full', className)}>
				<div className="flex h-full">
					<div className="w-1/2 relative border-r-2 border-gray-200">
						<ImageList />
					</div>
					<div className="w-1/2 relative overflow-auto">
						<ChatList messages={messages} isLoading={isLoading} />
						<ChatScrollAnchor trackVisibility={isLoading} />
					</div>
				</div>
			</div>
			<ChatPanel
				id={id}
				isLoading={isLoading}
				stop={stop}
				append={append}
				reload={reload}
				messages={messages}
				input={input}
				setInput={setInput}
			/>
		</>
	);
}
