import { useState, useEffect, useCallback } from "react";
import { API_BASE_URL, getAuthToken } from "~/lib/api";
import { logger } from "~/lib/logger";

export interface AppNotification {
  id: number;
  user: string;
  type: string;
  reference_id: number;
  action: string;
  content: string;
  status: number;
  created_at: string;
  updated_at: string | null;
}

export function useNotifications() {
  const [notifications, setNotifications] = useState<AppNotification[]>([]);
  const [loading, setLoading] = useState(false);
  const [showPanel, setShowPanel] = useState(false);
  const [unreadCount, setUnreadCount] = useState(0);
  const hasUnread = unreadCount > 0;

  const fetchNotifications = useCallback(async () => {
    const token = getAuthToken();
    if (!token) return;

    setLoading(true);
    try {
      const response = await fetch(`${API_BASE_URL}/notifications`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${token}`,
          "Content-Type": "application/json",
        },
      });

      if (response.ok) {
        const data = await response.json();
        if (data.status && data.data) {
          setNotifications(data.data);
          const count = data.data.filter(
            (n: AppNotification) => n.status === 0,
          ).length;
          setUnreadCount(count);
        }
      }
    } catch (error) {
      logger.error("Error fetching notifications:", error);
    } finally {
      setLoading(false);
    }
  }, []);

  const togglePanel = useCallback(() => {
    setShowPanel((prev) => !prev);
  }, []);

  const closePanel = useCallback(() => {
    setShowPanel(false);
  }, []);

  return {
    notifications,
    loading,
    showPanel,
    unreadCount,
    hasUnread,
    fetchNotifications,
    togglePanel,
    closePanel,
  };
}

export function formatNotificationTime(dateString: string): string {
  const date = new Date(dateString);
  const now = new Date();
  const diffInHours = Math.floor(
    (now.getTime() - date.getTime()) / (1000 * 60 * 60),
  );

  if (diffInHours < 1) return "Just now";
  if (diffInHours < 24) return `${diffInHours}h ago`;
  return `${Math.floor(diffInHours / 24)}d ago`;
}
