'use client';

/**
 * AdminInbox — admin notification inbox page component.
 *
 * Subscribes to the admin's personal channel (`live:admin:<adminUserId>`)
 * and the shared system channel (`live:admin:system`) via WebSocket.
 * Both channels invalidate the shared notifications query on new events,
 * so the inbox stays in sync with the top-bar NotificationBell.
 *
 * Wraps itself in HydratedIsland to provide QueryClient + live WS lifecycle.
 */

import { useCallback } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { useT } from '@/lib/i18n/react';
import { useLive, useLiveNotifications } from '@/lib/hooks/use-live-notifications';
import { HydratedIsland } from '@/components/HydratedIsland';
import { AdminPanel } from '@/components/ui/domain/admin/AdminPanel';
import { NotificationList } from '@/features/notifications/NotificationList';
import { LiveBadge } from '@/components/ui/notification/LiveBadge';

export interface AdminInboxProps {
  adminUserId: string;
}

function AdminInboxInner({ adminUserId }: AdminInboxProps) {
  const t = useT('admin_inbox');
  const qc = useQueryClient();
  const connected = useLiveNotifications();

  const refresh = useCallback(() => {
    void qc.invalidateQueries({ queryKey: ['notifications'] });
  }, [qc]);

  // Subscribe to personal admin channel for assignment events.
  useLive(`live:admin:${adminUserId}`, () => refresh());

  // Subscribe to system-wide admin channel for system health + broadcast events.
  useLive('live:admin:system', () => refresh());

  return (
    <AdminPanel title={t('heading')} toolbar={<LiveBadge connected={connected} />}>
      <p className="text-text-secondary px-4 pb-2 text-sm">{t('description')}</p>
      <NotificationList />
    </AdminPanel>
  );
}

export function AdminInbox({ adminUserId }: AdminInboxProps) {
  return (
    <HydratedIsland>
      <AdminInboxInner adminUserId={adminUserId} />
    </HydratedIsland>
  );
}
