// @design-system: domain/chat — ThreadList
import { useQuery } from '@tanstack/react-query';
import { useT, useLocale } from '@/lib/i18n/react';
import { formatRelative } from '@/lib/format';
import { Card } from '@/components/ui/layout/Card';
import { EmptyState } from '@/components/ui/feedback/EmptyState';
import { ErrorState } from '@/components/ui/feedback/ErrorState';
import { ChatSkeleton, SkeletonGuard } from '@/components/ui/feedback/Skeleton';
import { Button } from '@/components/ui/primitives/Button';
import type { EnrichedChatThread } from '@/server/db/queries/chat-threads';

export function ThreadList() {
  const t = useT('chat');
  const tCommon = useT('common');
  const { locale } = useLocale();
  const { data, isLoading, isError, refetch } = useQuery<{ items: EnrichedChatThread[] }>({
    queryKey: ['chat', 'threads'],
    queryFn: async () => {
      const res = await fetch('/api/chat/threads', { credentials: 'same-origin' });
      const body = (await res.json()) as {
        ok: boolean;
        data?: { items: EnrichedChatThread[] };
        error?: string;
      };
      if (!body.ok) throw new Error(body.error ?? 'load failed');
      return body.data!;
    },
  });

  if (isLoading && !data) {
    return (
      <div aria-busy="true" role="status">
        <span className="sr-only">{t('loading')}</span>
        <SkeletonGuard>
          <ChatSkeleton variant="list" count={5} />
        </SkeletonGuard>
      </div>
    );
  }
  if (isError) {
    return (
      <ErrorState
        title={tCommon('error_loading')}
        action={
          <Button variant="secondary" size="sm" onClick={() => refetch()}>
            {tCommon('retry')}
          </Button>
        }
      />
    );
  }
  if (!data || data.items.length === 0) {
    return <EmptyState title={t('empty_title')} description={t('empty_body')} />;
  }

  return (
    <ul data-skeleton-ready className="flex flex-col gap-[var(--space-2)]">
      {data.items.map((thread) => (
        <li key={thread.id}>
          <a href={`/threads/${thread.id}`} className="block">
            <Card className="p-[var(--space-4)]">
              <div className="font-semibold">{thread.title ?? t('untitled')}</div>
              {thread.counterpartyName && (
                <span className="text-text-secondary text-xs">{thread.counterpartyName}</span>
              )}
              {thread.lastMessagePreview && (
                <p className="text-text-secondary line-clamp-1 text-sm">
                  {thread.lastMessagePreview}
                </p>
              )}
              {thread.lastMessageAt && (
                <time
                  dateTime={new Date(thread.lastMessageAt).toISOString()}
                  className="text-sm text-[var(--color-text-muted)]"
                  suppressHydrationWarning
                >
                  {formatRelative(thread.lastMessageAt, locale)}
                </time>
              )}
            </Card>
          </a>
        </li>
      ))}
    </ul>
  );
}
