import { type ReactElement } from 'react';
import styled from '@lilith/ui-styled-components';
import { MessageSquare } from 'lucide-react';
import type { Conversation } from '@/types';

const List = styled.ul`
  list-style: none;
  margin: 0;
  padding: 0;
  overflow-y: auto;
  flex: 1;
`;

const Item = styled.li<{ $selected: boolean }>`
  display: flex;
  flex-direction: column;
  gap: 3px;
  padding: 12px 16px;
  cursor: pointer;
  border-bottom: 1px solid #1e1e2a;
  background: ${({ $selected }) => ($selected ? 'rgba(201,168,76,0.12)' : 'transparent')};
  transition: background 0.1s;

  &:hover {
    background: ${({ $selected }) => ($selected ? 'rgba(201,168,76,0.14)' : '#13131a')};
  }
`;

const Name = styled.span<{ $selected: boolean }>`
  font-size: 13px;
  font-weight: 600;
  color: ${({ $selected }) => ($selected ? '#c9a84c' : '#e0e0f0')};
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
`;

const Meta = styled.span`
  font-size: 11px;
  color: #8a8a9a;
`;

const GroupBadge = styled.span`
  display: inline-block;
  font-size: 10px;
  padding: 1px 6px;
  background: rgba(138,138,154,0.15);
  border-radius: 10px;
  color: #8a8a9a;
  margin-left: 6px;
`;

function formatRelative(iso: string | null): string {
  if (!iso) return '';
  const d = new Date(iso);
  const now = Date.now();
  const diff = now - d.getTime();
  if (diff < 60_000) return 'just now';
  if (diff < 3_600_000) return `${Math.floor(diff / 60_000)}m ago`;
  if (diff < 86_400_000) return `${Math.floor(diff / 3_600_000)}h ago`;
  return d.toLocaleDateString();
}

interface ConversationListProps {
  conversations: Conversation[];
  selectedId: string | null;
  onSelect: (id: string) => void;
}

export function ConversationList({ conversations, selectedId, onSelect }: ConversationListProps): ReactElement {
  return (
    <List role="listbox" aria-label="Conversations">
      {conversations.map((conv) => (
        <Item
          key={conv.id}
          $selected={conv.id === selectedId}
          onClick={() => onSelect(conv.id)}
          role="option"
          aria-selected={conv.id === selectedId}
          tabIndex={0}
          onKeyDown={(e) => {
            if (e.key === 'Enter' || e.key === ' ') {
              e.preventDefault();
              onSelect(conv.id);
            }
          }}
        >
          <Name $selected={conv.id === selectedId}>
            <MessageSquare size={11} style={{ marginRight: 5, opacity: 0.5, verticalAlign: 'middle' }} />
            {conv.displayName || conv.participants[0] || 'Unknown'}
            {conv.isGroup && <GroupBadge>group</GroupBadge>}
          </Name>
          <Meta>
            {conv.messageCount} msg{conv.messageCount !== 1 ? 's' : ''}{' '}
            {conv.lastMessageAt && `· ${formatRelative(conv.lastMessageAt)}`}
          </Meta>
        </Item>
      ))}
    </List>
  );
}
