import { useCallback, useEffect, useMemo, useState } from "react";
import {
  listHandoverNotifications,
  markAllHandoverNotificationsRead,
  markHandoverNotificationRead
} from "../services/notificationsApi.js";

const DEFAULT_POLL_MS = 45000;

export function useHandoverNotifications({ pollMs = DEFAULT_POLL_MS, enabled = true } = {}) {
  const [items, setItems] = useState([]);
  const [loading, setLoading] = useState(Boolean(enabled));
  const [error, setError] = useState("");

  const refresh = useCallback(async () => {
    if (!enabled) {
      setItems([]);
      return { items: [], unreadCount: 0 };
    }
    const result = await listHandoverNotifications();
    setItems(result.items);
    return result;
  }, [enabled]);

  useEffect(() => {
    if (!enabled) {
      setItems([]);
      setLoading(false);
      return undefined;
    }

    let cancelled = false;
    setLoading(true);
    refresh()
      .catch((err) => {
        if (!cancelled) {
          setError(err?.response?.data?.message || err.message || "Could not load notifications");
          setItems([]);
        }
      })
      .finally(() => {
        if (!cancelled) setLoading(false);
      });

    const timer = setInterval(() => {
      refresh().catch(() => {});
    }, pollMs);

    return () => {
      cancelled = true;
      clearInterval(timer);
    };
  }, [enabled, pollMs, refresh]);

  const unread = useMemo(() => items.filter((row) => !row.read_at), [items]);

  const markRead = useCallback(async (row) => {
    if (!row?.notification_id) return;
    await markHandoverNotificationRead(row.notification_id);
    setItems((prev) =>
      prev.map((item) =>
        item.notification_id === row.notification_id
          ? { ...item, read_at: item.read_at || new Date().toISOString() }
          : item
      )
    );
  }, []);

  const markAllRead = useCallback(async () => {
    await markAllHandoverNotificationsRead();
    setItems((prev) =>
      prev.map((item) => ({
        ...item,
        read_at: item.read_at || new Date().toISOString()
      }))
    );
  }, []);

  return {
    items,
    unread,
    unreadCount: unread.length,
    loading,
    error,
    refresh,
    markRead,
    markAllRead
  };
}
