import { type ReactElement } from 'react';
import styled from '@lilith/ui-styled-components';
import { Mail } 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 Subject = styled.span<{ $selected: boolean }>`
  font-size: 13px;
  font-weight: 600;
  color: ${({ $selected }) => ($selected ? '#c9a84c' : '#e0e0f0')};
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
`;

const Sender = styled.span`
  font-size: 11px;
  color: #8a8a9a;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
`;

function formatRelative(iso: string | null): string {
  if (!iso) return '';
  const d = new Date(iso);
  const diff = Date.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 MailListProps {
  conversations: Conversation[];
  selectedId: string | null;
  onSelect: (id: string) => void;
}

export function MailList({ conversations, selectedId, onSelect }: MailListProps): ReactElement {
  return (
    <List role="listbox" aria-label="Email threads">
      {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);
            }
          }}
        >
          <Subject $selected={conv.id === selectedId}>
            <Mail size={10} style={{ marginRight: 5, opacity: 0.5, verticalAlign: 'middle' }} />
            {conv.displayName || '(no subject)'}
          </Subject>
          <Sender>
            {conv.participants[0] ?? ''}{' '}
            {conv.lastMessageAt && `· ${formatRelative(conv.lastMessageAt)}`}
          </Sender>
        </Item>
      ))}
    </List>
  );
}
