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

interface ThreadMessage {
  id: string;
  content: string;
  senderJid: string;
  senderName: string | null;
  tags: string[];
  status: string;
  createdAt: string;
}

interface ThreadDetail {
  id: string;
  topic: string | null;
  sourceGroupName: string;
  messageCount: number;
  lastActivityAt: string;
  createdAt: string;
  messages: ThreadMessage[];
}

const STATUS_COLORS: Record<string, string> = {
  APPROVED: 'text-green-600',
  PENDING: 'text-amber-600',
  REJECTED: 'text-red-600',
  RAW: 'text-gray-400',
  DNC: 'text-gray-400',
  DISTRIBUTED: 'text-blue-600',
};

export default async function ThreadDetailPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;

  let thread: ThreadDetail | null = null;
  let error: string | null = null;

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

  if (error || !thread) {
    return (
      <div className="max-w-2xl">
        <Link href="/threads" className="text-sm text-blue-600 hover:underline mb-4 inline-block">&larr; Back to threads</Link>
        <p className="text-red-600 text-sm">{error ?? 'Thread not found'}</p>
      </div>
    );
  }

  return (
    <div className="max-w-2xl">
      <Link href="/threads" className="text-sm text-blue-600 hover:underline mb-4 inline-block">&larr; Back to threads</Link>

      <div className="mb-6">
        <h1 className="text-xl font-semibold">
          {thread.topic ?? `Thread ${thread.id.slice(0, 8)}`}
        </h1>
        <p className="text-sm text-gray-500 mt-1">
          {thread.sourceGroupName} &middot; {thread.messageCount} messages &middot; last activity {new Date(thread.lastActivityAt).toLocaleDateString()}
        </p>
      </div>

      <div className="flex flex-col gap-3">
        {thread.messages.map((msg) => (
          <div key={msg.id} className="border border-gray-200 rounded-lg p-4">
            <div className="flex items-center justify-between mb-2">
              <div className="text-xs text-gray-500">
                <span className="font-medium text-gray-700">{msg.senderName ?? msg.senderJid}</span>
                <span className="mx-1">&middot;</span>
                <span>{new Date(msg.createdAt).toLocaleString()}</span>
              </div>
              <div className="flex items-center gap-2">
                <span className={`text-xs font-medium ${STATUS_COLORS[msg.status] ?? 'text-gray-500'}`}>
                  {msg.status}
                </span>
                <Link href={`/messages/${msg.id}`} className="text-xs text-blue-600 hover:underline">
                  View
                </Link>
              </div>
            </div>
            <p className="text-sm text-gray-900 whitespace-pre-wrap">{msg.content}</p>
            {msg.tags.length > 0 && (
              <div className="flex flex-wrap gap-1 mt-2">
                {msg.tags.map((tag) => (
                  <span key={tag} className="rounded-full bg-blue-50 px-2 py-0.5 text-xs text-blue-600">{tag}</span>
                ))}
              </div>
            )}
          </div>
        ))}
      </div>
    </div>
  );
}
