import { Avatar } from '../ui/Avatar';

interface ChatListItemProps {
  chat: {
    id: string;
    name: string;
    avatarSet?: string[];
    latestMessage?: {
      text?: string;
      created_at?: string;
    } | null;
    targetProfile?: {
      gender?: string;
      age?: number;
      isMajestic?: boolean;
    } | null;
    discoveredLocation?: string | null;
  };
  onClick?: () => void;
}

export function ChatListItem({ chat, onClick }: ChatListItemProps) {
  const avatar = chat.avatarSet?.[0];
  const message = chat.latestMessage;
  const locationText = typeof chat.discoveredLocation === 'string' ? chat.discoveredLocation : '';

  // Parse the message if it's a string (from API)
  const messageData = typeof message === 'string' ? JSON.parse(message) : message;
  const messageText = messageData?.text || 'No messages yet';
  const messageTime = messageData?.created_at;
  const hasMessage = messageData?.text;

  const formatTime = (dateStr: string) => {
    const date = new Date(dateStr);
    const now = new Date();
    const diffDays = Math.floor((now.getTime() - date.getTime()) / (1000 * 60 * 60 * 24));

    if (diffDays === 0) {
      return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    } else if (diffDays === 1) {
      return 'Yesterday';
    } else if (diffDays < 7) {
      return date.toLocaleDateString([], { weekday: 'short' });
    } else {
      return date.toLocaleDateString([], { month: 'short', day: 'numeric' });
    }
  };

  return (
    <div
      onClick={onClick}
      className="
        group
        p-4 rounded-xl
        bg-[var(--color-surface)]
        hover:bg-[var(--color-surface-elevated)]
        flex items-center gap-4
        cursor-pointer
        transition-all duration-300
        border border-transparent
        hover:border-white/5
      "
    >
      {/* Avatar with online indicator possibility */}
      <div className="relative flex-shrink-0">
        <Avatar src={avatar} size="lg" />
        {/* Could add online status here */}
      </div>

      {/* Content */}
      <div className="flex-1 min-w-0">
        {/* Top row: Name and time */}
        <div className="flex items-center justify-between mb-1.5">
          <div className="flex items-center gap-2 min-w-0">
            <h3 className="
              font-semibold
              text-[var(--color-text-primary)]
              truncate
              group-hover:text-white
              transition-colors
            ">
              {chat.name}
            </h3>
            {chat.targetProfile?.isMajestic && (
              <div className="
                w-5 h-5 rounded-full
                bg-amber-500/20
                flex items-center justify-center
                flex-shrink-0
              ">
                <svg viewBox="0 0 24 24" fill="currentColor" className="w-3 h-3 text-amber-400">
                  <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" />
                </svg>
              </div>
            )}
          </div>
          {messageTime && (
            <span className="
              text-xs font-medium
              text-[var(--color-text-muted)]
              flex-shrink-0
              ml-3
            ">
              {formatTime(messageTime)}
            </span>
          )}
        </div>

        {/* Message preview */}
        <p className={`
          text-sm truncate
          ${hasMessage
            ? 'text-[var(--color-text-secondary)]'
            : 'text-[var(--color-text-muted)] italic'
          }
        `}>
          {messageText}
        </p>

        {locationText && (
          <div className="flex items-center gap-1 mt-1 text-xs text-[var(--color-text-muted)]">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="w-3 h-3 flex-shrink-0">
              <path strokeLinecap="round" strokeLinejoin="round" d="M15 10.5a3 3 0 11-6 0 3 3 0 016 0z" />
              <path strokeLinecap="round" strokeLinejoin="round" d="M19.5 10.5c0 7.142-7.5 11.25-7.5 11.25S4.5 17.642 4.5 10.5a7.5 7.5 0 1115 0z" />
            </svg>
            <span className="truncate">{locationText}</span>
          </div>
        )}
      </div>

      {/* Chevron indicator */}
      <div className="
        flex-shrink-0
        opacity-0 group-hover:opacity-100
        transition-opacity duration-200
        text-[var(--color-text-muted)]
      ">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="w-5 h-5">
          <path strokeLinecap="round" strokeLinejoin="round" d="M8.25 4.5l7.5 7.5-7.5 7.5" />
        </svg>
      </div>
    </div>
  );
}
