'use client';

import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import type { Chat } from '@/lib/types';
import { cn } from '@/lib/utils';
import { CheckCheck } from 'lucide-react';

interface ChatItemProps {
    chat: Chat;
    active?: boolean;
    onClick?: () => void;
}

export function ChatItem({ chat, active, onClick }: ChatItemProps) {
    return (
        <div
            onClick={onClick}
            className={cn(
                'mx-1 flex cursor-pointer items-start gap-3 border-b border-border px-2 py-3 transition-colors hover:bg-accent/50',
                active && 'bg-accent',
            )}
        >
            <div className="relative">
                <Avatar className="h-12 w-12">
                    <AvatarImage src={chat.avatar || '/placeholder.svg'} alt={chat.name} />
                    <AvatarFallback>{chat.name.slice(0, 2).toUpperCase()}</AvatarFallback>
                </Avatar>
                {chat.online && <div className="absolute right-0 bottom-0 h-3 w-3 rounded-full border-2 border-background bg-green-500" />}
            </div>

            <div className="min-w-0 flex-1">
                <div className="mb-1 flex items-center justify-between gap-2">
                    <div className="flex items-center gap-2">
                        <h3 className="truncate text-sm font-semibold">{chat.name}</h3>
                    </div>
                    <span className="text-xs whitespace-nowrap text-text-gray">{chat.timestamp}</span>
                </div>

                <div className="flex items-center justify-between gap-2">
                    <p
                        className={cn('truncate text-sm', chat.typing ? 'text-green-600' : 'text-text-gray', {
                            'font-bold text-black': chat.unreadCount,
                        })}
                    >
                        {chat.lastMessage}
                    </p>
                    <div className="flex items-center gap-2">
                        {chat.unreadCount && (
                            <span className="flex size-5 items-center justify-center rounded-full border bg-success text-xs font-bold text-white">
                                {chat.unreadCount}
                            </span>
                        )}
                        {!chat.unreadCount && !chat.typing && <CheckCheck className="h-4 w-4 text-text-gray" />}
                    </div>
                </div>
            </div>
        </div>
    );
}
