/**
 * useAlertAnalytics Hook
 * Fetches analytics data from backend API
 */

import { useState, useEffect, useCallback } from 'react';
import { NotificationData } from './useNotifications';
import type { AlertCategory } from '../utils/alertHelpers';
import { useCurrentTenant } from '../stores/tenant.store';
import { useAuthUser } from '../stores/auth.store';

export interface AlertTrendData {
  date: string;
  count: number;
  urgentCount: number;
  highCount: number;
  mediumCount: number;
  lowCount: number;
}

export interface AlertAnalytics {
  trends: AlertTrendData[];
  averageResponseTime: number;
  topCategories: Array<{ category: AlertCategory | string; count: number; percentage: number }>;
  totalAlerts: number;
  resolvedAlerts: number;
  activeAlerts: number;
  resolutionRate: number;
  predictedDailyAverage: number;
  busiestDay: string;
}

/**
 * Hook to fetch and display alert analytics from backend
 */
export function useAlertAnalytics(alerts: NotificationData[], days: number = 7): AlertAnalytics {
  const currentTenant = useCurrentTenant();
  const user = useAuthUser();
  const tenantId = currentTenant?.id || user?.tenant_id;

  const [analytics, setAnalytics] = useState<AlertAnalytics>({
    trends: [],
    averageResponseTime: 0,
    topCategories: [],
    totalAlerts: 0,
    resolvedAlerts: 0,
    activeAlerts: 0,
    resolutionRate: 0,
    predictedDailyAverage: 0,
    busiestDay: 'N/A',
  });

  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Fetch analytics from backend
  const fetchAnalytics = useCallback(async () => {
    if (!tenantId) {
      console.warn('[useAlertAnalytics] No tenant ID found, skipping analytics fetch');
      return;
    }

    console.log('[useAlertAnalytics] Fetching analytics for tenant:', tenantId, 'days:', days);
    setLoading(true);
    setError(null);

    try {
      const { getAlertAnalytics } = await import('../api/services/alert_analytics');
      const data = await getAlertAnalytics(tenantId, days);
      console.log('[useAlertAnalytics] Received data from API:', data);
      setAnalytics(data);
      console.log('[useAlertAnalytics] Analytics state updated');
    } catch (err) {
      console.error('[useAlertAnalytics] Failed to fetch alert analytics:', err);
      setError(err instanceof Error ? err.message : 'Failed to fetch analytics');

      // Fallback to empty state on error
      setAnalytics({
        trends: [],
        averageResponseTime: 0,
        topCategories: [],
        totalAlerts: alerts.length,
        resolvedAlerts: 0,
        activeAlerts: alerts.length,
        resolutionRate: 0,
        predictedDailyAverage: 0,
        busiestDay: 'N/A',
      });
    } finally {
      setLoading(false);
    }
  }, [tenantId, days, alerts.length]);

  // Fetch on mount and when days changes
  useEffect(() => {
    fetchAnalytics();
  }, [fetchAnalytics]);

  // Refetch when new alerts arrive (debounced)
  useEffect(() => {
    const timer = setTimeout(() => {
      fetchAnalytics();
    }, 2000);

    return () => clearTimeout(timer);
  }, [alerts.length, fetchAnalytics]);

  return analytics;
}

/**
 * Hook to export analytics tracking methods
 * Uses backend API for persistent tracking across devices
 */
export function useAlertAnalyticsTracking() {
  const { trackAlertInteraction } = useAlertInteractions();

  const trackAcknowledgment = useCallback(async (alertId: string) => {
    try {
      await trackAlertInteraction(alertId, 'acknowledged');
    } catch (error) {
      console.error('Failed to track acknowledgment:', error);
    }
  }, [trackAlertInteraction]);

  const trackResolution = useCallback(async (alertId: string) => {
    try {
      await trackAlertInteraction(alertId, 'resolved');
    } catch (error) {
      console.error('Failed to track resolution:', error);
    }
  }, [trackAlertInteraction]);

  const trackSnooze = useCallback(async (alertId: string, duration: string) => {
    try {
      await trackAlertInteraction(alertId, 'snoozed', { duration });
    } catch (error) {
      console.error('Failed to track snooze:', error);
    }
  }, [trackAlertInteraction]);

  const trackDismiss = useCallback(async (alertId: string, reason?: string) => {
    try {
      await trackAlertInteraction(alertId, 'dismissed', { reason });
    } catch (error) {
      console.error('Failed to track dismiss:', error);
    }
  }, [trackAlertInteraction]);

  return {
    trackAcknowledgment,
    trackResolution,
    trackSnooze,
    trackDismiss,
  };
}

/**
 * Hook for tracking alert interactions
 */
function useAlertInteractions() {
  const currentTenant = useCurrentTenant();
  const user = useAuthUser();
  const tenantId = currentTenant?.id || user?.tenant_id;

  const trackAlertInteraction = useCallback(async (
    alertId: string,
    interactionType: 'acknowledged' | 'resolved' | 'snoozed' | 'dismissed',
    metadata?: Record<string, any>
  ) => {
    if (!tenantId) {
      console.warn('No tenant ID found, skipping interaction tracking');
      return;
    }

    const { trackAlertInteraction: apiTrack } = await import('../api/services/alert_analytics');
    await apiTrack(tenantId, alertId, interactionType, metadata);
  }, [tenantId]);

  return { trackAlertInteraction };
}
