/**
 * 客服 Agent 状态组件 - 紧凑版
 * 用于顶部状态栏显示
 */

import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
import { Settings, RefreshCw } from "lucide-react";
import { supabase } from "@/integrations/supabase/client";
import { cn } from "@/lib/utils";
import serviceAvatar from "@/assets/agents/service-avatar.png";

interface AgentDashboardProps {
  onSettingsClick?: () => void;
  compact?: boolean;
}

export function AgentDashboard({ onSettingsClick, compact = false }: AgentDashboardProps) {
  const [status, setStatus] = useState<'online' | 'busy' | 'offline'>('online');
  const [metrics, setMetrics] = useState({
    todayHandled: 0,
    autoResolveRate: 0,
    pending: 0,
  });
  const [loading, setLoading] = useState(true);

  const fetchMetrics = async () => {
    setLoading(true);
    try {
      const { data: { session } } = await supabase.auth.getSession();
      if (!session) return;

      // 获取今日处理数
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      
      const { count: todayCount } = await supabase
        .from('after_sales_requests')
        .select('*', { count: 'exact', head: true })
        .gte('updated_at', today.toISOString())
        .in('status', ['approved', 'rejected', 'completed']);

      // 获取待处理数
      const { count: pendingCount } = await supabase
        .from('after_sales_requests')
        .select('*', { count: 'exact', head: true })
        .eq('status', 'pending');

      setMetrics({
        todayHandled: todayCount || 0,
        autoResolveRate: 85, // 模拟数据
        pending: pendingCount || 0,
      });
    } catch (err) {
      console.error('Failed to fetch metrics:', err);
    } finally {
      setLoading(false);
    }
  };

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

  const statusConfig = {
    online: { label: '运行中', color: 'bg-green-500' },
    busy: { label: '忙碌', color: 'bg-yellow-500' },
    offline: { label: '离线', color: 'bg-muted-foreground' },
  };

  if (compact) {
    return (
      <div className="flex items-center gap-3 px-4 py-2 bg-card rounded-lg border">
        <Avatar className="h-8 w-8">
          <AvatarImage src={serviceAvatar} alt="小服" />
          <AvatarFallback>服</AvatarFallback>
        </Avatar>
        <div className="flex items-center gap-2">
          <span className="font-medium text-sm">小服</span>
          <Badge variant="outline" className="text-xs gap-1">
            <span className={cn("h-1.5 w-1.5 rounded-full", statusConfig[status].color)} />
            {statusConfig[status].label}
          </Badge>
        </div>
        <div className="flex items-center gap-4 ml-4 text-sm text-muted-foreground">
          <span>今日处理: <span className="text-foreground font-medium">{metrics.todayHandled}</span></span>
          <span>待处理: <span className={cn("font-medium", metrics.pending > 0 ? "text-orange-500" : "text-foreground")}>{metrics.pending}</span></span>
        </div>
        <Button variant="ghost" size="icon" className="h-7 w-7 ml-auto" onClick={onSettingsClick}>
          <Settings className="h-4 w-4" />
        </Button>
      </div>
    );
  }

  return (
    <div className="flex items-center justify-between p-4 bg-card rounded-lg border">
      <div className="flex items-center gap-4">
        <Avatar className="h-12 w-12">
          <AvatarImage src={serviceAvatar} alt="小服" />
          <AvatarFallback>服</AvatarFallback>
        </Avatar>
        <div>
          <div className="flex items-center gap-2">
            <span className="font-semibold">小服</span>
            <Badge variant="outline" className="text-xs gap-1">
              <span className={cn("h-2 w-2 rounded-full", statusConfig[status].color)} />
              {statusConfig[status].label}
            </Badge>
          </div>
          <p className="text-sm text-muted-foreground">客服AI助手</p>
        </div>
      </div>
      
      <div className="flex items-center gap-6">
        <div className="text-center">
          <div className="text-2xl font-bold">{metrics.todayHandled}</div>
          <div className="text-xs text-muted-foreground">今日处理</div>
        </div>
        <div className="text-center">
          <div className="text-2xl font-bold">{metrics.autoResolveRate}%</div>
          <div className="text-xs text-muted-foreground">自动解决率</div>
        </div>
        <div className="text-center">
          <div className={cn("text-2xl font-bold", metrics.pending > 0 && "text-orange-500")}>{metrics.pending}</div>
          <div className="text-xs text-muted-foreground">待处理</div>
        </div>
      </div>

      <div className="flex items-center gap-2">
        <Button variant="ghost" size="icon" onClick={fetchMetrics} disabled={loading}>
          <RefreshCw className={cn("h-4 w-4", loading && "animate-spin")} />
        </Button>
        <Button variant="ghost" size="icon" onClick={onSettingsClick}>
          <Settings className="h-4 w-4" />
        </Button>
      </div>
    </div>
  );
}
