import Link from 'next/link';
import { redirect } from 'next/navigation';
import type { Metadata } from 'next';
import { getAccountToken } from '@/lib/account-session';
import { backendApi, BackendApiError, type ApiConversation } from '@/lib/backend-api';
import { ROUTES, messageThreadRoute } from '@/lib/routes';

export const metadata: Metadata = { title: 'Messages' };
export const dynamic = 'force-dynamic';

// The guide documents `unread_count` explicitly but not a full field list
// for the rest of a conversation summary — try several plausible names for
// the other participant's label and the last-message preview rather than
// assuming one exact shape.
function participantLabel(c: ApiConversation): string {
  const candidates = [c.other_participant_name, c.participant_name, c.vendor_name, c.buyer_name, c.store_name, c.name];
  const found = candidates.find((v): v is string => typeof v === 'string' && v.trim().length > 0);
  return found ?? `Conversation #${c.id}`;
}

function preview(c: ApiConversation): string | null {
  const candidates = [c.last_message, c.latest_message, c.preview];
  const found = candidates.find((v): v is string => typeof v === 'string' && v.trim().length > 0);
  return found ?? null;
}

export default async function MessagesInboxPage() {
  const token = getAccountToken();
  if (!token) {
    redirect(`${ROUTES.login}?redirect=${ROUTES.messages}`);
    return;
  }

  let conversations: ApiConversation[] = [];
  let loadError: string | null = null;
  try {
    const res = await backendApi.getConversations(token);
    conversations = res.data;
  } catch (err) {
    loadError = err instanceof BackendApiError ? err.message : 'Could not load your messages right now.';
  }

  return (
    <div className="space-y-5">
      <h1 className="font-serif text-2xl font-bold text-navy-800">Messages</h1>

      {loadError && (
        <p className="rounded-md border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">{loadError}</p>
      )}

      {!loadError && conversations.length === 0 && (
        <p className="text-sm text-navy-600">No conversations yet.</p>
      )}

      {conversations.length > 0 && (
        <div className="card divide-y divide-navy-100">
          {conversations.map((c) => (
            <Link
              key={c.id}
              href={messageThreadRoute(c.id)}
              className="flex items-center justify-between gap-4 p-4 hover:bg-white"
            >
              <div className="min-w-0">
                <p className="truncate text-sm font-semibold text-navy-800">{participantLabel(c)}</p>
                {preview(c) && <p className="truncate text-xs text-navy-500">{preview(c)}</p>}
              </div>
              {c.unread_count > 0 && (
                <span className="shrink-0 rounded-full bg-gold-500 px-2 py-0.5 text-[11px] font-bold text-navy-800">
                  {c.unread_count}
                </span>
              )}
            </Link>
          ))}
        </div>
      )}
    </div>
  );
}
