'use client';

import { useQuery } from '@tanstack/react-query';
import { formatDistanceToNow } from 'date-fns';
import { Mail } from 'lucide-react';

import { apiFetch } from '@/lib/api/client';
import { EmptyState } from '@/components/shared/empty-state';
import { Skeleton } from '@/components/ui/skeleton';

interface Thread {
  id: string;
  subject: string;
  snippet: string | null;
  lastMessageAt: string;
  participants: string[];
  unreadCount: number;
}

interface ThreadsResponse {
  data: Thread[];
  total: number;
}

export function EmailThreadsList() {
  const { data, isLoading } = useQuery<ThreadsResponse>({
    queryKey: ['email', 'threads'],
    queryFn: () => apiFetch<ThreadsResponse>('/api/v1/email/threads'),
  });

  if (isLoading) {
    // Skeleton rows shaped like the real list so the layout doesn't pop.
    return (
      <div className="rounded-lg border divide-y">
        {Array.from({ length: 4 }).map((_, i) => (
          <div key={i} className="p-3 space-y-2">
            <div className="flex items-center justify-between gap-2">
              <Skeleton className="h-4 w-1/3" aria-hidden />
              <Skeleton className="h-3 w-16" aria-hidden />
            </div>
            <Skeleton className="h-3 w-1/2" aria-hidden />
            <Skeleton className="h-3 w-2/3" aria-hidden />
          </div>
        ))}
      </div>
    );
  }

  const threads = data?.data ?? [];

  if (threads.length === 0) {
    return (
      <EmptyState
        icon={Mail}
        title="No email threads yet"
        description="Connect an account and trigger a sync to see incoming threads here."
      />
    );
  }

  return (
    <div className="rounded-lg border divide-y">
      {threads.map((t) => (
        <div key={t.id} className="p-3 hover:bg-muted/40">
          <div className="flex items-center justify-between gap-2">
            <div className="text-sm font-medium truncate">{t.subject || '(no subject)'}</div>
            <div className="text-xs text-muted-foreground shrink-0">
              {formatDistanceToNow(new Date(t.lastMessageAt), { addSuffix: true })}
            </div>
          </div>
          <div className="text-xs text-muted-foreground truncate">{t.participants.join(', ')}</div>
          {t.snippet && (
            <div className="text-xs text-muted-foreground mt-1 line-clamp-1">{t.snippet}</div>
          )}
          {t.unreadCount > 0 && (
            <span className="inline-block mt-1 rounded-full bg-primary/10 px-2 py-0.5 text-xs text-primary">
              {t.unreadCount} unread
            </span>
          )}
        </div>
      ))}
    </div>
  );
}
