'use client';

import { formatDistanceToNow } from 'date-fns';
import { tr } from 'date-fns/locale';
import type { Conversation } from '@/lib/hooks/useChat';

interface ConversationItemProps {
  conversation: Conversation;
  isActive: boolean;
  currentUserId: string;
  onClick: () => void;
}

const ROLE_LABELS: Record<string, string> = {
  ADMIN: 'Yönetici',
  TEACHER: 'Öğretmen',
  PARENT: 'Veli',
};

function UserAvatar({ name, role }: { name: string; role: string }) {
  const initial = name.charAt(0).toUpperCase();
  const colorMap: Record<string, string> = {
    ADMIN: 'bg-violet-100 text-violet-700',
    TEACHER: 'bg-sky-100 text-sky-700',
    PARENT: 'bg-teal-100 text-teal-700',
  };
  const color = colorMap[role] ?? 'bg-slate-100 text-slate-700';

  return (
    <div
      className={`flex h-10 w-10 shrink-0 items-center justify-center rounded-full text-sm font-bold ${color}`}
    >
      {initial}
    </div>
  );
}

export function ConversationItem({
  conversation,
  isActive,
  currentUserId,
  onClick,
}: ConversationItemProps) {
  const { otherUser, lastMessage, unreadCount, updatedAt } = conversation;
  const name = otherUser?.fullName ?? 'Bilinmeyen';
  const role = otherUser?.role ?? '';
  const hasUnread = unreadCount > 0;

  const timeStr = updatedAt
    ? formatDistanceToNow(new Date(updatedAt), { addSuffix: true, locale: tr })
    : '';

  const lastBody =
    lastMessage
      ? lastMessage.senderId === currentUserId
        ? `Siz: ${lastMessage.body}`
        : lastMessage.type === 'SYSTEM'
        ? lastMessage.body
        : lastMessage.body
      : 'Henüz mesaj yok';

  return (
    <button
      onClick={onClick}
      className={`w-full px-4 py-3 text-left transition-colors ${
        isActive
          ? 'bg-indigo-50 border-r-2 border-r-indigo-600'
          : 'hover:bg-slate-50 border-r-2 border-r-transparent'
      }`}
    >
      <div className="flex items-start gap-3">
        <UserAvatar name={name} role={role} />

        <div className="min-w-0 flex-1">
          <div className="flex items-center justify-between gap-2">
            <span
              className={`truncate text-sm ${
                hasUnread ? 'font-semibold text-slate-900' : 'font-medium text-slate-700'
              }`}
            >
              {name}
            </span>
            <span className="shrink-0 text-[11px] text-slate-400">{timeStr}</span>
          </div>

          <div className="mt-0.5 flex items-center justify-between gap-2">
            <span
              className={`truncate text-xs ${
                hasUnread ? 'font-medium text-slate-700' : 'text-slate-400'
              }`}
            >
              {lastBody}
            </span>
            {hasUnread && (
              <span className="flex h-5 min-w-5 shrink-0 items-center justify-center rounded-full bg-indigo-600 px-1.5 text-[10px] font-bold text-white">
                {unreadCount > 9 ? '9+' : unreadCount}
              </span>
            )}
          </div>

          <span className="mt-0.5 block text-[11px] text-slate-400">
            {ROLE_LABELS[role] ?? role}
          </span>
        </div>
      </div>
    </button>
  );
}
