/**
 * 业务警报 Realtime 订阅 Hook
 * 
 * 订阅 business_alerts 表的实时变更，
 * 当有新警报插入时自动通知前端
 */

import { useEffect, useState, useCallback } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';

export type AlertSeverity = 'info' | 'warning' | 'critical';
export type AlertCategory = 'inventory' | 'order' | 'marketing' | 'finance' | 'service' | 'system';

export interface BusinessAlert {
  id: string;
  alert_type: string;
  category: AlertCategory;
  severity: AlertSeverity;
  title: string;
  description: string;
  data: Record<string, unknown>;
  target_agent: string;
  is_read: boolean;
  is_dismissed: boolean;
  created_at: string;
  read_at: string | null;
  expires_at: string | null;
}

interface UseBusinessAlertsOptions {
  /** 过滤特定 Agent 的警报 */
  targetAgent?: string;
  /** 是否只显示未读警报 */
  unreadOnly?: boolean;
  /** 是否显示 Toast 通知 */
  showToast?: boolean;
}

export function useBusinessAlerts(options: UseBusinessAlertsOptions = {}) {
  const { targetAgent, unreadOnly = true, showToast = true } = options;
  const [alerts, setAlerts] = useState<BusinessAlert[]>([]);
  const [loading, setLoading] = useState(true);
  const [unreadCount, setUnreadCount] = useState(0);
  const { toast } = useToast();

  // 加载警报
  const fetchAlerts = useCallback(async () => {
    try {
      let query = supabase
        .from('business_alerts')
        .select('*')
        .eq('is_dismissed', false)
        .order('created_at', { ascending: false })
        .limit(50);

      if (targetAgent) {
        query = query.eq('target_agent', targetAgent);
      }

      if (unreadOnly) {
        query = query.eq('is_read', false);
      }

      const { data, error } = await query;

      if (error) {
        console.error('[useBusinessAlerts] Fetch error:', error);
        return;
      }

      // Type assertion since Supabase types may not be updated yet
      const typedData = (data || []) as unknown as BusinessAlert[];
      setAlerts(typedData);
      setUnreadCount(typedData.filter(a => !a.is_read).length);
    } catch (err) {
      console.error('[useBusinessAlerts] Error:', err);
    } finally {
      setLoading(false);
    }
  }, [targetAgent, unreadOnly]);

  // 标记警报为已读
  const markAsRead = useCallback(async (alertId: string) => {
    const { error } = await supabase
      .from('business_alerts')
      .update({ is_read: true, read_at: new Date().toISOString() })
      .eq('id', alertId);

    if (!error) {
      setAlerts(prev => prev.map(a => 
        a.id === alertId ? { ...a, is_read: true, read_at: new Date().toISOString() } : a
      ));
      setUnreadCount(prev => Math.max(0, prev - 1));
    }
  }, []);

  // 忽略警报
  const dismissAlert = useCallback(async (alertId: string) => {
    const { error } = await supabase
      .from('business_alerts')
      .update({ is_dismissed: true })
      .eq('id', alertId);

    if (!error) {
      setAlerts(prev => prev.filter(a => a.id !== alertId));
    }
  }, []);

  // 标记所有为已读
  const markAllAsRead = useCallback(async () => {
    let query = supabase
      .from('business_alerts')
      .update({ is_read: true, read_at: new Date().toISOString() })
      .eq('is_read', false);

    if (targetAgent) {
      query = query.eq('target_agent', targetAgent);
    }

    const { error } = await query;

    if (!error) {
      setAlerts(prev => prev.map(a => ({ ...a, is_read: true, read_at: new Date().toISOString() })));
      setUnreadCount(0);
    }
  }, [targetAgent]);

  // 初始加载
  useEffect(() => {
    fetchAlerts();
  }, [fetchAlerts]);

  // Realtime 订阅
  useEffect(() => {
    const channel = supabase
      .channel('business_alerts_realtime')
      .on(
        'postgres_changes',
        {
          event: 'INSERT',
          schema: 'public',
          table: 'business_alerts',
        },
        (payload) => {
          console.log('[useBusinessAlerts] New alert received:', payload);
          const newAlert = payload.new as unknown as BusinessAlert;

          // 检查是否匹配过滤条件
          if (targetAgent && newAlert.target_agent !== targetAgent) {
            return;
          }

          // 添加到列表
          setAlerts(prev => [newAlert, ...prev]);
          setUnreadCount(prev => prev + 1);

          // 显示 Toast 通知
          if (showToast) {
            const variant = newAlert.severity === 'critical' ? 'destructive' : 'default';
            toast({
              title: getSeverityEmoji(newAlert.severity) + ' ' + newAlert.title,
              description: newAlert.description,
              variant,
            });
          }
        }
      )
      .on(
        'postgres_changes',
        {
          event: 'UPDATE',
          schema: 'public',
          table: 'business_alerts',
        },
        (payload) => {
          const updatedAlert = payload.new as unknown as BusinessAlert;
          setAlerts(prev => prev.map(a => a.id === updatedAlert.id ? updatedAlert : a));
        }
      )
      .on(
        'postgres_changes',
        {
          event: 'DELETE',
          schema: 'public',
          table: 'business_alerts',
        },
        (payload) => {
          const deletedId = (payload.old as { id: string }).id;
          setAlerts(prev => prev.filter(a => a.id !== deletedId));
        }
      )
      .subscribe((status) => {
        console.log('[useBusinessAlerts] Subscription status:', status);
      });

    return () => {
      supabase.removeChannel(channel);
    };
  }, [targetAgent, showToast, toast]);

  return {
    alerts,
    loading,
    unreadCount,
    markAsRead,
    dismissAlert,
    markAllAsRead,
    refetch: fetchAlerts,
  };
}

function getSeverityEmoji(severity: AlertSeverity): string {
  switch (severity) {
    case 'critical': return '🚨';
    case 'warning': return '⚠️';
    case 'info': return 'ℹ️';
    default: return '📢';
  }
}

/**
 * 手动触发监控检查
 */
export async function triggerInsightsMonitor(): Promise<{ success: boolean; message: string }> {
  try {
    const { data, error } = await supabase.functions.invoke('insights-monitor');
    
    if (error) {
      console.error('[triggerInsightsMonitor] Error:', error);
      return { success: false, message: error.message };
    }
    
    return data as { success: boolean; message: string };
  } catch (err) {
    console.error('[triggerInsightsMonitor] Error:', err);
    return { success: false, message: String(err) };
  }
}
