import { sessionUser } from '@/auth';
import { Card } from '../ui/Card';
import { IconExclamationTriangle } from '../ui/Icons';
import Link from 'next/link';
import { ChatWithMessages } from '@/lib/types';
import { dbGetUser } from '@/lib/db/functions';
import Avatar from '../Avatar';

export interface TopPrompt {
  chat: ChatWithMessages;
  userId?: string | null;
}

export default async function TopPrompt({ chat, userId }: TopPrompt) {
  const authorId = chat.userId;
  // 1. Viewer logged in, Viewer = Author
  if (userId && authorId === userId) {
    return null;
  }
  // 2. Viewer logged in, No Author
  if (userId && !authorId) {
    return null;
  }
  // 3. Author, but is not Viewer
  if (authorId && authorId !== userId) {
    const chatAuthor = authorId ? await dbGetUser(authorId) : null;
    return (
      <Card className="group py-2 px-4 flex flex-row items-center">
        <p className="leading-normal text-sm">Authored by</p>
        <div className="flex-1 px-1 ml-2 flex flex-row items-center space-x-2">
          <Avatar name={chatAuthor?.name} avatar={chatAuthor?.avatar} />
          <p className="font-medium">{chatAuthor?.name ?? 'Unknown'}</p>
        </div>
      </Card>
    );
  }
  // 4. No author, Viewer not logged in
  if (!userId && !authorId) {
    return (
      <Card className="group py-2 px-4 flex items-center">
        <div className="bg-background flex size-8 shrink-0 select-none items-center justify-center rounded-md">
          <IconExclamationTriangle className="font-medium" />
        </div>
        <div className="flex-1 px-1 ml-2 overflow-hidden">
          <p className="leading-normal font-medium">
            <Link href="/sign-in" className="underline">
              Sign in
            </Link>{' '}
            to save and revisit your chat history!
          </p>
        </div>
      </Card>
    );
  }
  return null;
}
