'use client';

import Link from 'next/link';
import { Briefcase, MessageCircle, UserRound } from 'lucide-react';
import {
  Conversation,
  conversationMatchesThread,
  getConversationOtherUser,
  getConversationTitle,
  getConversationSubtitle,
  formatMessageTime,
} from '@/lib/messages';
import { UnreadBadge } from '@/components/ui/unread-badge';
import { UserAvatar } from '@/components/ui/UserAvatar';
import { JOBS_FEATURE_ENABLED } from '@/lib/features';
import { cn } from '@/lib/utils';
import { formatLastActive, isRecentlyActive } from '@/lib/lastActive';
import { getMessagesEmptyCopy } from '@/components/messages/MessagesInboxHeader';

interface ConversationListProps {
  conversations: Conversation[];
  currentUserId: string;
  basePath: string;
  activeId?: string;
  role: 'customer' | 'worker';
  searchQuery?: string;
  filter?: 'all' | 'unread';
}

export function ConversationList({
  conversations,
  currentUserId,
  basePath,
  activeId,
  role,
  searchQuery = '',
  filter = 'all',
}: ConversationListProps) {
  if (conversations.length === 0) {
    const isSearching = searchQuery.trim().length > 0;
    const isUnreadFilter = filter === 'unread';
    return (
      <div className="flex flex-col items-center justify-center px-6 py-16 text-center">
        <div className="mb-4 flex h-14 w-14 items-center justify-center bg-[var(--home-sand)] text-[var(--home-ink)]">
          <MessageCircle className="h-7 w-7" />
        </div>
        <p className="font-semibold text-[var(--home-ink)]">
          {isSearching
            ? 'No matching conversations'
            : isUnreadFilter
              ? 'No unread messages'
              : 'No conversations yet'}
        </p>
        <p className="mt-2 max-w-xs text-sm leading-relaxed text-muted">
          {isSearching
            ? 'Try a different name.'
            : isUnreadFilter
              ? 'You’re all caught up. Switch to All to see your chats.'
              : getMessagesEmptyCopy(role)}
        </p>
        {role === 'worker' && !isSearching && !isUnreadFilter && JOBS_FEATURE_ENABLED && (
          <Link
            href="/worker/jobs"
            className="mt-5 inline-flex items-center gap-1.5 text-sm font-semibold text-[var(--home-amber)] hover:underline"
          >
            <Briefcase className="h-4 w-4" />
            Browse available jobs
          </Link>
        )}
        {role === 'worker' && !isSearching && !isUnreadFilter && !JOBS_FEATURE_ENABLED && (
          <Link
            href="/worker/profile"
            className="mt-5 inline-flex items-center gap-1.5 text-sm font-semibold text-[var(--home-amber)] hover:underline"
          >
            <UserRound className="h-4 w-4" />
            Complete your profile
          </Link>
        )}
        {role === 'customer' && !isSearching && !isUnreadFilter && !JOBS_FEATURE_ENABLED && (
          <Link
            href="/customer/workers"
            className="mt-5 inline-flex items-center gap-1.5 text-sm font-semibold text-[var(--home-amber)] hover:underline"
          >
            Browse workers
          </Link>
        )}
      </div>
    );
  }

  return (
    <ul className="divide-y divide-[#ebe6db]">
      {conversations.map((conversation) => {
        const lastMessage = conversation.messages[0];
        const isActive = conversationMatchesThread(conversation, activeId);
        const isOwn = lastMessage?.senderId === currentUserId;
        const unreadCount = conversation.unreadCount ?? 0;
        const hasUnread = unreadCount > 0;
        const otherUser = getConversationOtherUser(conversation, currentUserId);
        const displayName = getConversationTitle(conversation, currentUserId);
        const subtitle = getConversationSubtitle(conversation);
        const lastActive = formatLastActive(otherUser?.lastActiveAt);

        return (
          <li key={conversation.id}>
            <Link
              href={`${basePath}/${conversation.id}`}
              className={cn(
                'flex gap-3 px-4 py-3.5 transition-colors',
                isActive
                  ? 'bg-white shadow-[inset_3px_0_0_var(--home-amber)]'
                  : 'hover:bg-white/80',
                hasUnread && !isActive && 'bg-[var(--home-sand)]/55'
              )}
            >
              <div className="relative shrink-0">
                <UserAvatar
                  firstName={otherUser?.firstName ?? displayName}
                  lastName={otherUser?.lastName ?? ''}
                  avatarUrl={otherUser?.avatarUrl}
                  size="sm"
                  rounded="none"
                  ringClassName="ring-1 ring-[#e2ddd2] shadow-none"
                />
                {isRecentlyActive(otherUser?.lastActiveAt) ? (
                  <span
                    className="absolute bottom-0 right-0 h-2.5 w-2.5 bg-emerald-500 ring-2 ring-white"
                    title="Active now"
                  />
                ) : null}
              </div>

              <div className="min-w-0 flex-1">
                <div className="flex items-start justify-between gap-2">
                  <div className="min-w-0">
                    <p
                      className={cn(
                        'truncate text-sm text-[var(--home-ink)]',
                        hasUnread ? 'font-bold' : 'font-semibold'
                      )}
                    >
                      {displayName}
                    </p>
                    <p className="mt-0.5 truncate text-[11px] text-muted">
                      {lastActive ? (
                        <span className="text-emerald-700">{lastActive}</span>
                      ) : (
                        subtitle
                      )}
                      {lastActive && subtitle !== 'Direct message' ? (
                        <span className="text-muted"> · {subtitle}</span>
                      ) : null}
                    </p>
                  </div>
                  <div className="flex shrink-0 flex-col items-end gap-1">
                    {lastMessage ? (
                      <span
                        className={cn(
                          'text-[11px] tabular-nums',
                          hasUnread
                            ? 'font-semibold text-[var(--home-amber)]'
                            : 'text-slate-400'
                        )}
                      >
                        {formatMessageTime(lastMessage.createdAt)}
                      </span>
                    ) : null}
                    {hasUnread ? <UnreadBadge count={unreadCount} /> : null}
                  </div>
                </div>

                {lastMessage ? (
                  <p
                    className={cn(
                      'mt-1.5 truncate text-sm',
                      hasUnread ? 'font-medium text-slate-800' : 'text-muted'
                    )}
                  >
                    {isOwn ? <span className="text-slate-400">You: </span> : null}
                    {lastMessage.content}
                  </p>
                ) : (
                  <p className="mt-1.5 truncate text-sm italic text-muted">
                    No messages yet — say hello
                  </p>
                )}
              </div>
            </Link>
          </li>
        );
      })}
    </ul>
  );
}
