'use client';

import { MediaDetails } from '@/lib/fetch';
import React from 'react';
import { ChatList } from '../chat/ChatList';
import useVisionAgent from '@/lib/hooks/useVisionAgent';
import { nanoid } from '@/lib/utils';
import { useScrollAnchor } from '@/lib/hooks/useScrollAnchor';
import { Composer } from '../chat/Composer';
import { useAtomValue } from 'jotai';
import { selectedMediaIdAtom } from '@/state/media';

export interface ChatProps {
  mediaList: MediaDetails[];
}

const ProjectChat: React.FC<ChatProps> = ({ mediaList }) => {
  const selectedMediaId = useAtomValue(selectedMediaIdAtom);
  // fallback to the first media
  const selectedMedia =
    mediaList.find(media => media.id === selectedMediaId) ?? mediaList[0];
  const { messages, append, reload, stop, isLoading, input, setInput } =
    useVisionAgent({
      url: selectedMedia.url,
      messages: [],
      user: 'does-not-matter@landing.ai',
      updatedAt: Date.now(),
    });

  const { messagesRef, scrollRef, visibilityRef, isAtBottom, scrollToBottom } =
    useScrollAnchor();

  return (
    <>
      <div className="h-full overflow-auto" ref={scrollRef}>
        <div className="pb-[200px] pt-4 md:pt-10" ref={messagesRef}>
          <ChatList messages={messages} session={null} />
          <div className="h-px w-full" ref={visibilityRef} />
        </div>
      </div>
      <div className="absolute inset-x-0 bottom-0 w-full h-[178px]">
        <Composer
          url={selectedMedia.url}
          isLoading={isLoading}
          stop={stop}
          append={append}
          reload={reload}
          messages={messages}
          input={input}
          setInput={setInput}
          isAtBottom={isAtBottom}
          scrollToBottom={scrollToBottom}
        />
      </div>
    </>
  );
};

export default ProjectChat;
