import Link from 'next/link';
import { apiFetch } from '../_lib/api';

interface ThreadSummary {
  id: string;
  topic: string | null;
  sourceGroupName: string;
  messageCount: number;
  lastActivityAt: string;
  createdAt: string;
}

export default async function ThreadsPage() {
  let threads: ThreadSummary[] = [];
  let error: string | null = null;

  try {
    const res = await apiFetch('/admin/threads');
    if (res.ok) {
      threads = await res.json();
    } else {
      error = `API returned ${res.status}`;
    }
  } catch {
    error = 'Failed to load threads';
  }

  return (
    <div className="max-w-4xl">
      <h1 className="text-xl font-semibold mb-6">Threads</h1>

      {error && (
        <p className="text-red-600 text-sm mb-4">{error}</p>
      )}

      {!error && threads.length === 0 && (
        <p className="text-gray-500 text-sm">No threads yet. Threads are created automatically when members reply to messages.</p>
      )}

      {threads.length > 0 && (
        <div className="border border-gray-200 rounded-lg divide-y divide-gray-100">
          {threads.map((thread) => (
            <Link
              key={thread.id}
              href={`/threads/${thread.id}`}
              className="flex items-start justify-between p-4 hover:bg-gray-50 transition-colors"
            >
              <div className="min-w-0 flex-1">
                <p className="text-sm font-medium text-gray-900 truncate">
                  {thread.topic ?? `Thread ${thread.id.slice(0, 8)}`}
                </p>
                <p className="text-xs text-gray-500 mt-0.5">{thread.sourceGroupName}</p>
              </div>
              <div className="ml-4 shrink-0 text-right">
                <span className="inline-flex items-center rounded-full bg-blue-50 px-2.5 py-0.5 text-xs font-medium text-blue-700">
                  {thread.messageCount} {thread.messageCount === 1 ? 'message' : 'messages'}
                </span>
                <p className="text-xs text-gray-400 mt-1">
                  {new Date(thread.lastActivityAt).toLocaleDateString()}
                </p>
              </div>
            </Link>
          ))}
        </div>
      )}
    </div>
  );
}
