"use client";

import {
  createContext,
  ReactNode,
  useCallback,
  useContext,
  useEffect,
  useState,
} from "react";
import { useAuth } from "@/lib/auth/auth-provider";
import { NotificationItem } from "@/lib/types";
import { fetchNotifications, markNotificationRead, markAllNotificationsRead } from "./notifications";

// Polling, not a WebSocket/Realtime subscription — same reasoning as
// admin-orders-provider.tsx and the User Panel's notifications (see
// sharednet-ui's NOTIFICATION_POLL_MS): Supabase Realtime had no
// MySQL equivalent to rebuild without a WebSocket server, which
// shared hosting can't run.
const NOTIFICATIONS_POLL_MS = 30_000;

interface AdminNotificationsContextValue {
  notifications: NotificationItem[];
  unreadCount: number;
  loading: boolean;
  error: string | null;
  refetch: () => Promise<void>;
  markRead: (id: string) => Promise<void>;
  markAllRead: () => Promise<void>;
}

const AdminNotificationsContext = createContext<AdminNotificationsContextValue | null>(null);

export function AdminNotificationsProvider({ children }: { children: ReactNode }) {
  const { user } = useAuth();
  const [notifications, setNotifications] = useState<NotificationItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const refetch = useCallback(async () => {
    if (!user) return;
    try {
      const result = await fetchNotifications();
      setNotifications(result);
      setError(null);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Couldn't load notifications.");
    } finally {
      setLoading(false);
    }
  }, [user]);

  useEffect(() => {
    if (!user) return;
    refetch();
    const interval = setInterval(refetch, NOTIFICATIONS_POLL_MS);
    window.addEventListener("focus", refetch);
    return () => {
      clearInterval(interval);
      window.removeEventListener("focus", refetch);
    };
  }, [user, refetch]);

  const value: AdminNotificationsContextValue = {
    notifications,
    unreadCount: notifications.filter((n) => !n.read).length,
    loading,
    error,
    refetch,
    markRead: async (id) => {
      setNotifications((prev) => prev.map((n) => (n.id === id ? { ...n, read: true } : n)));
      await markNotificationRead(id);
    },
    markAllRead: async () => {
      if (!user) return;
      setNotifications((prev) => prev.map((n) => ({ ...n, read: true })));
      await markAllNotificationsRead();
    },
  };

  return (
    <AdminNotificationsContext.Provider value={value}>
      {children}
    </AdminNotificationsContext.Provider>
  );
}

export function useAdminNotifications() {
  const ctx = useContext(AdminNotificationsContext);
  if (!ctx) throw new Error("useAdminNotifications must be used within AdminNotificationsProvider");
  return ctx;
}
