"use client";

import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import {
  adminNotificationControllerGetNotificationsV1 as getNotifications,
  adminNotificationControllerGetUnreadCountV1 as getUnreadCount,
  adminNotificationControllerMarkAsReadV1 as markNotificationAsRead,
  adminNotificationControllerMarkAllAsReadV1 as markAllNotificationsAsRead,
  adminNotificationControllerDeleteNotificationV1 as deleteNotification,
} from "@/api/user/admin-notifications/admin-notifications";
import type {
  NotificationControllerGetNotificationsV1Params as NotificationParams,
  NotificationControllerGetNotificationsV1Type as NotificationType,
} from "@/api/user/generated.schemas";

// eslint-disable-next-line @typescript-eslint/no-explicit-any
type Notification = any;

const NOTIFICATIONS_KEY = "admin-notifications";
const UNREAD_COUNT_KEY = "admin-notifications-unread-count";
const POLLING_INTERVAL = 30000; // 30 seconds

interface UseAdminNotificationsOptions {
  enabled?: boolean;
  params?: NotificationParams;
  enablePolling?: boolean;
}

export const useAdminNotifications = (options: UseAdminNotificationsOptions = {}) => {
  const { enabled = true, params, enablePolling = true } = options;
  const queryClient = useQueryClient();

  // Fetch notifications list
  const notificationsQuery = useQuery({
    queryKey: [NOTIFICATIONS_KEY, params],
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    queryFn: () => getNotifications(params) as Promise<any>,
    enabled,
    refetchInterval: enablePolling ? POLLING_INTERVAL : false,
    staleTime: 10000, // 10 seconds
    retry: 1, // Only retry once
    retryDelay: 1000,
    gcTime: 60000, // Keep in cache for 1 minute
  });

  // Fetch unread count (lighter endpoint for badge)
  const unreadCountQuery = useQuery({
    queryKey: [UNREAD_COUNT_KEY],
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    queryFn: () => getUnreadCount() as Promise<any>,
    enabled,
    refetchInterval: enablePolling ? POLLING_INTERVAL : false,
    staleTime: 10000,
    retry: 1,
    retryDelay: 1000,
    gcTime: 60000,
  });

  // Mark single notification as read
  const markAsReadMutation = useMutation({
    mutationFn: (uuid: string) => markNotificationAsRead(uuid),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [NOTIFICATIONS_KEY] });
      queryClient.invalidateQueries({ queryKey: [UNREAD_COUNT_KEY] });
    },
  });

  // Mark all notifications as read
  const markAllAsReadMutation = useMutation({
    mutationFn: () => markAllNotificationsAsRead(),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [NOTIFICATIONS_KEY] });
      queryClient.invalidateQueries({ queryKey: [UNREAD_COUNT_KEY] });
    },
  });

  // Delete notification
  const deleteMutation = useMutation({
    mutationFn: (uuid: string) => deleteNotification(uuid),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [NOTIFICATIONS_KEY] });
      queryClient.invalidateQueries({ queryKey: [UNREAD_COUNT_KEY] });
    },
  });

  // Derived data - handle error state gracefully
  const notifications = notificationsQuery.data?.data?.notifications || [];
  const totalCount = notificationsQuery.data?.data?.total_count || 0;
  const totalPages = notificationsQuery.data?.data?.total_pages || 1;
  const currentPage = notificationsQuery.data?.data?.page || 1;

  // Use dedicated unread count endpoint, fallback to calculated, 0 on error
  const unreadCount = notificationsQuery.isError
    ? 0
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    : (unreadCountQuery.data?.data?.unread_count ?? notifications.filter((n: any) => !n.is_read).length);

  // Consider loading complete if error occurred (don't block UI)
  const effectiveLoading = notificationsQuery.isLoading && !notificationsQuery.isError;

  return {
    // Data
    notifications,
    unreadCount,
    totalCount,
    totalPages,
    currentPage,

    // Loading states
    isLoading: effectiveLoading,
    isFetching: notificationsQuery.isFetching,
    isError: notificationsQuery.isError,
    error: notificationsQuery.error,

    // Actions
    markAsRead: markAsReadMutation.mutate,
    markAllAsRead: markAllAsReadMutation.mutate,
    deleteNotification: deleteMutation.mutate,

    // Action states
    isMarkingAsRead: markAsReadMutation.isPending,
    isMarkingAllAsRead: markAllAsReadMutation.isPending,
    isDeleting: deleteMutation.isPending,

    // Refetch
    refetch: () => {
      notificationsQuery.refetch();
      unreadCountQuery.refetch();
    },
  };
};

// Hook for dropdown (only recent notifications)
export const useAdminNotificationDropdown = (enabled = true) => {
  return useAdminNotifications({
    enabled,
    params: { limit: 5, page: 1 },
    enablePolling: true,
  });
};

// Hook for full notifications page
export const useAdminNotificationPage = (params: NotificationParams = {}) => {
  return useAdminNotifications({
    enabled: true,
    params: { limit: 50, ...params },
    enablePolling: false, // Manual refresh on page
  });
};

// Export types
export type { Notification, NotificationType, NotificationParams };
