'use client';

import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { useAdminInbox } from '@/lib/queries/use-admin';
import { useMarkAllNotificationsRead } from '@/lib/queries/use-notifications';
import { NotificationRow } from '@/components/notifications/notification-row';

type Filter = 'all' | 'unread';

export function InboxClient() {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const filter: Filter = searchParams.get('filter') === 'unread' ? 'unread' : 'all';
  const setFilter = (next: Filter) => {
    const params = new URLSearchParams(searchParams.toString());
    if (next === 'all') params.delete('filter');
    else params.set('filter', next);
    const qs = params.toString();
    router.replace(qs ? `${pathname}?${qs}` : pathname);
  };
  const { data, isLoading, isError } = useAdminInbox(filter);
  const markAllRead = useMarkAllNotificationsRead();

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

  return (
    <div>
      <header className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-slate-900">Inbox</h1>
          <p className="mt-1 text-sm text-slate-500">
            Disputes, store moderation, and admin team coordination.
          </p>
        </div>
        <button
          onClick={() => markAllRead.mutate()}
          disabled={markAllRead.isPending}
          className="rounded-md border border-slate-300 px-3 py-1 text-sm hover:bg-slate-50 disabled:opacity-50"
        >
          Mark all read
        </button>
      </header>

      <div className="mt-4 flex gap-2">
        {(['all', 'unread'] as const).map((f) => (
          <button
            key={f}
            onClick={() => setFilter(f)}
            className={`rounded-md px-3 py-1 text-xs font-medium ${
              filter === f
                ? 'bg-slate-900 text-white'
                : 'border border-slate-300 text-slate-600 hover:bg-slate-50'
            }`}
          >
            {f === 'all' ? 'All' : 'Unread'}
          </button>
        ))}
      </div>

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

      <div className="mt-4 rounded-lg border border-slate-200 bg-white">
        {isLoading && (
          <p className="px-4 py-6 text-center text-sm text-slate-400">Loading…</p>
        )}
        {!isLoading && items.length === 0 && (
          <p className="px-4 py-6 text-center text-sm text-slate-400">No notifications.</p>
        )}
        {items.map((item) => (
          <NotificationRow key={item.id} item={item} />
        ))}
      </div>
    </div>
  );
}
