/**
 * 实时警报横幅组件
 * 
 * 显示在页面顶部的警报通知栏，
 * 展示最新的未读警报并提供快速操作
 */

import React from 'react';
import { X, Bell, AlertTriangle, AlertCircle, Info, ChevronRight, CheckCheck } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { ScrollArea } from '@/components/ui/scroll-area';
import {
  Sheet,
  SheetContent,
  SheetHeader,
  SheetTitle,
  SheetTrigger,
} from '@/components/ui/sheet';
import { useBusinessAlerts, type BusinessAlert, type AlertSeverity } from '@/hooks/useBusinessAlerts';
import { cn } from '@/lib/utils';
import { formatDistanceToNow } from 'date-fns';
import { zhCN } from 'date-fns/locale';

interface RealtimeAlertBannerProps {
  targetAgent?: string;
  className?: string;
}

export function RealtimeAlertBanner({ targetAgent, className }: RealtimeAlertBannerProps) {
  const { alerts, unreadCount, markAsRead, dismissAlert, markAllAsRead } = useBusinessAlerts({
    targetAgent,
    unreadOnly: false,
    showToast: true,
  });

  // 获取最紧急的未读警报
  const urgentAlert = alerts.find(a => !a.is_read && a.severity === 'critical');
  const hasUnread = unreadCount > 0;

  return (
    <Sheet>
      <SheetTrigger asChild>
        <Button
          variant="ghost"
          size="sm"
          className={cn(
            "relative gap-2",
            hasUnread && "animate-pulse",
            className
          )}
        >
          <Bell className="h-4 w-4" />
          {hasUnread && (
            <Badge 
              variant="destructive" 
              className="absolute -top-1 -right-1 h-5 w-5 p-0 flex items-center justify-center text-xs"
            >
              {unreadCount > 9 ? '9+' : unreadCount}
            </Badge>
          )}
          {urgentAlert && (
            <span className="text-xs text-destructive hidden sm:inline">
              {urgentAlert.title}
            </span>
          )}
        </Button>
      </SheetTrigger>

      <SheetContent className="w-full sm:max-w-md">
        <SheetHeader className="flex flex-row items-center justify-between">
          <SheetTitle className="flex items-center gap-2">
            <Bell className="h-5 w-5" />
            业务警报
            {hasUnread && (
              <Badge variant="secondary">{unreadCount} 未读</Badge>
            )}
          </SheetTitle>
          {hasUnread && (
            <Button variant="ghost" size="sm" onClick={markAllAsRead}>
              <CheckCheck className="h-4 w-4 mr-1" />
              全部已读
            </Button>
          )}
        </SheetHeader>

        <ScrollArea className="h-[calc(100vh-120px)] mt-4">
          <div className="space-y-3 pr-4">
            {alerts.length === 0 ? (
              <div className="text-center py-8 text-muted-foreground">
                <Bell className="h-12 w-12 mx-auto mb-3 opacity-20" />
                <p>暂无警报</p>
              </div>
            ) : (
              alerts.map(alert => (
                <AlertCard
                  key={alert.id}
                  alert={alert}
                  onRead={() => markAsRead(alert.id)}
                  onDismiss={() => dismissAlert(alert.id)}
                />
              ))
            )}
          </div>
        </ScrollArea>
      </SheetContent>
    </Sheet>
  );
}

interface AlertCardProps {
  alert: BusinessAlert;
  onRead: () => void;
  onDismiss: () => void;
}

function AlertCard({ alert, onRead, onDismiss }: AlertCardProps) {
  const Icon = getSeverityIcon(alert.severity);
  const colorClass = getSeverityColor(alert.severity);

  return (
    <div
      className={cn(
        "p-3 rounded-lg border transition-all",
        !alert.is_read && "bg-accent/50 border-l-4",
        !alert.is_read && colorClass,
        alert.is_read && "opacity-60"
      )}
    >
      <div className="flex items-start gap-3">
        <Icon className={cn("h-5 w-5 mt-0.5 flex-shrink-0", colorClass)} />
        
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 mb-1">
            <h4 className="font-medium text-sm truncate">{alert.title}</h4>
            <Badge variant="outline" className="text-xs flex-shrink-0">
              {getCategoryLabel(alert.category)}
            </Badge>
          </div>
          
          <p className="text-sm text-muted-foreground line-clamp-2">
            {alert.description}
          </p>
          
          <div className="flex items-center justify-between mt-2">
            <span className="text-xs text-muted-foreground">
              {formatDistanceToNow(new Date(alert.created_at), { 
                addSuffix: true, 
                locale: zhCN 
              })}
            </span>
            
            <div className="flex items-center gap-1">
              {!alert.is_read && (
                <Button
                  variant="ghost"
                  size="sm"
                  className="h-7 px-2 text-xs"
                  onClick={onRead}
                >
                  已读
                </Button>
              )}
              <Button
                variant="ghost"
                size="sm"
                className="h-7 w-7 p-0"
                onClick={onDismiss}
              >
                <X className="h-3 w-3" />
              </Button>
            </div>
          </div>
        </div>
        
        <ChevronRight className="h-4 w-4 text-muted-foreground flex-shrink-0" />
      </div>
    </div>
  );
}

function getSeverityIcon(severity: AlertSeverity) {
  switch (severity) {
    case 'critical': return AlertTriangle;
    case 'warning': return AlertCircle;
    case 'info': return Info;
    default: return Bell;
  }
}

function getSeverityColor(severity: AlertSeverity): string {
  switch (severity) {
    case 'critical': return 'text-destructive border-l-destructive';
    case 'warning': return 'text-orange-500 border-l-orange-500';
    case 'info': return 'text-blue-500 border-l-blue-500';
    default: return 'text-muted-foreground';
  }
}

function getCategoryLabel(category: string): string {
  const labels: Record<string, string> = {
    inventory: '库存',
    order: '订单',
    marketing: '营销',
    finance: '财务',
    service: '售后',
    system: '系统',
  };
  return labels[category] || category;
}
