"use client";

import { useCallback } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useRouter } from "@/i18n/routing";
import {
  fetchNotifications,
  markNotificationsRead,
  type CafeNotification,
} from "@/lib/api/notifications";
import { useAuthStore } from "@/lib/stores/auth.store";
import { notificationDestinationFromStore } from "@/lib/notifications/notification-routes";

type UseNotificationsFeedOptions = {
  unreadOnly?: boolean;
  limit?: number;
};

type OpenNotificationOptions = {
  /** Navigate to the related page after marking read (notifications page only). */
  navigate?: boolean;
};

/**
 * Notification list + read actions. The live SignalR connection is owned by
 * useOrderAlerts (mounted once in the dashboard shell), which invalidates the
 * ["notifications", cafeId] query on each incoming event — so this hook just
 * reads the shared query (no second hub connection) and polls as a backstop.
 */
export function useNotificationsFeed(options: UseNotificationsFeedOptions = {}) {
  const { unreadOnly = false, limit = 50 } = options;
  const cafeId = useAuthStore((s) => s.user?.cafeId);
  const router = useRouter();
  const qc = useQueryClient();

  const queryKey = ["notifications", cafeId, unreadOnly] as const;

  const { data, isLoading, isFetching, refetch } = useQuery({
    queryKey,
    queryFn: () => fetchNotifications(cafeId!, unreadOnly, limit),
    enabled: !!cafeId,
    refetchInterval: 60_000,
  });

  const refresh = useCallback(() => {
    if (!cafeId) return;
    void qc.invalidateQueries({ queryKey: ["notifications", cafeId] });
  }, [qc, cafeId]);

  const openNotification = useCallback(
    async (n: CafeNotification, opts: OpenNotificationOptions = {}) => {
      if (!cafeId) return;
      if (!n.isRead) await markNotificationsRead(cafeId, { ids: [n.id] });
      refresh();
      if (!opts.navigate) return;
      const dest = notificationDestinationFromStore(n);
      if (dest) router.push(dest);
    },
    [cafeId, refresh, router]
  );

  const markAllRead = useCallback(async () => {
    if (!cafeId) return;
    await markNotificationsRead(cafeId, { all: true });
    refresh();
  }, [cafeId, refresh]);

  return {
    cafeId,
    items: data?.items ?? [],
    unreadCount: data?.unreadCount ?? 0,
    isLoading,
    isFetching,
    refetch,
    refresh,
    openNotification,
    markAllRead,
  };
}
