'use client';

import Link from 'next/link';
import { useMyThreads } from '@/lib/queries/use-my-threads';
import { useSelectedStoreId } from '@/lib/stores/store-context';

export function MessagesInboxClient() {
  const storeId = useSelectedStoreId();
  const { data, isLoading, isError } = useMyThreads(storeId);
  const rows = data?.data ?? [];

  return (
    <div className="mx-auto max-w-3xl px-4 py-6">
      <h1 className="text-xl font-bold text-slate-900">Messages</h1>
      <p className="mt-1 text-sm text-slate-500">
        Conversations across all your orders.
      </p>

      {isError && (
        <p className="mt-4 rounded bg-red-50 p-3 text-sm text-red-700">
          Couldn&apos;t load your messages.
        </p>
      )}

      <div className="mt-4 divide-y divide-slate-100 rounded-lg border border-slate-200 bg-white">
        {isLoading && (
          <p className="px-4 py-6 text-sm text-slate-400">Loading…</p>
        )}
        {!isLoading && rows.length === 0 && (
          <p className="px-4 py-8 text-center text-sm text-slate-400">
            No conversations yet.
          </p>
        )}
        {rows.map((t) => (
          <Link
            key={t.thread_id}
            href={`/seller/orders/${t.order_id}#messages`}
            className="flex items-center justify-between gap-3 px-4 py-3 hover:bg-slate-50"
          >
            <div className="min-w-0">
              <div className="font-medium text-slate-900">
                {t.counterparty_name ?? '—'}
              </div>
              <div className="truncate text-sm text-slate-500">
                {t.last_message_snippet ?? 'No messages yet.'}
              </div>
            </div>
            <div className="flex items-center gap-3 text-xs text-slate-400">
              {t.last_message_at && (
                <time>{new Date(t.last_message_at).toLocaleDateString()}</time>
              )}
              {t.unread_count > 0 && (
                <span className="rounded-full bg-forest-600 px-2 py-0.5 text-white">
                  {t.unread_count}
                </span>
              )}
            </div>
          </Link>
        ))}
      </div>
    </div>
  );
}
