import { useState, useEffect } from 'react';
import { statsAPI } from '../utils/api';

export interface Alert {
  id: string;
  type: string;
  priority: string;
  title: string;
  message: string;
  count?: number;
  isResolved: boolean;
  // Optional fields for detailed alerts
  itemId?: string;
  itemName?: string;
  category?: string;
  quantity?: number;
  unit?: string;
  expiryDate?: string;
  daysUntilExpiry?: number;
  daysExpired?: number;
  lowStockThreshold?: number;
  createdAt?: Date | string;
}

export const useAlerts = () => {
  const [alerts, setAlerts] = useState<Alert[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchAlerts = async () => {
    try {
      setLoading(true);
      setError(null);
      const data = await statsAPI.getAlerts();
      setAlerts(data.alerts || []);
    } catch (err: any) {
      setError(err.message || 'Failed to fetch alerts');
      setAlerts([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchAlerts();
  }, []);

  return { alerts, loading, error, refetch: fetchAlerts };
};

