'use client';

import { PropsWithChildren } from 'react';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import { cn } from '@/lib/utils';
import { ChatEntity } from '@/lib/types';
import Image from 'next/image';
import clsx from 'clsx';

type ChatCardProps = PropsWithChildren<{
  chat: ChatEntity;
}>;

export const ChatCardLayout: React.FC<
  PropsWithChildren<{ link: string; classNames?: clsx.ClassValue }>
> = ({ link, children, classNames }) => {
  return (
    <Link
      className={cn(
        'p-2 m-2 bg-background l:h-[250px] rounded-xl shadow-md flex items-center border border-transparent hover:border-gray-500 transition-all cursor-pointer',
        classNames,
      )}
      href={link}
    >
      {children}
    </Link>
  );
};

const ChatCard: React.FC<ChatCardProps> = ({ chat }) => {
  const { id: chatIdFromParam } = useParams();
  const { id, url, messages, user } = chat;
  const firstMessage = messages?.[0]?.content.slice(0, 50);
  return (
    <ChatCardLayout
      link={`/chat/${id}`}
      classNames={chatIdFromParam === id && 'border-gray-500'}
    >
      <div className="overflow-hidden flex items-center size-full">
        <Image
          src={url}
          alt={url}
          width={50}
          height={50}
          className="rounded w-1/4 "
        />
        <p className="text-sm w-3/4 ml-3">
          {firstMessage ?? '(No messages yet)'}
        </p>
      </div>
    </ChatCardLayout>
  );
};

export default ChatCard;
