/**
 * 通用 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 { AI_AGENTS } from "@/types/agents";

type AgentType = 'manager' | 'product' | 'marketing' | 'service' | 'finance';

interface GenericAgentDashboardProps {
  agentType: AgentType;
  onSettingsClick?: () => void;
  compact?: boolean;
}

interface AgentMetrics {
  primary: number;
  secondary: number;
  pending: number;
  primaryLabel: string;
  secondaryLabel: string;
  pendingLabel: string;
}

// 不同模块的指标获取逻辑
const getMetricsFetcher = (agentType: AgentType) => {
  return async (): Promise<AgentMetrics> => {
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    
    switch (agentType) {
      case 'product': {
        const { count: totalProducts } = await supabase
          .from('products')
          .select('*', { count: 'exact', head: true })
          .eq('is_active', true);
        
        const { count: lowStock } = await supabase
          .from('products')
          .select('*', { count: 'exact', head: true })
          .lt('stock_quantity', 10)
          .eq('is_active', true);
        
        return {
          primary: totalProducts || 0,
          secondary: 85, // 模拟优化率
          pending: lowStock || 0,
          primaryLabel: '商品数',
          secondaryLabel: '库存健康度',
          pendingLabel: '低库存'
        };
      }
      
      case 'marketing': {
        const { count: activeCampaigns } = await supabase
          .from('marketing_campaigns')
          .select('*', { count: 'exact', head: true })
          .eq('status', 'active');
        
        const { count: pendingCampaigns } = await supabase
          .from('marketing_campaigns')
          .select('*', { count: 'exact', head: true })
          .eq('status', 'pending');
        
        return {
          primary: activeCampaigns || 0,
          secondary: 78, // 模拟转化率
          pending: pendingCampaigns || 0,
          primaryLabel: '进行中活动',
          secondaryLabel: '转化率',
          pendingLabel: '待审批'
        };
      }
      
      case 'finance': {
        const { count: todayOrders } = await supabase
          .from('orders')
          .select('*', { count: 'exact', head: true })
          .gte('created_at', today.toISOString())
          .eq('status', 'paid');
        
        const { count: pendingRefunds } = await supabase
          .from('after_sales_requests')
          .select('*', { count: 'exact', head: true })
          .eq('status', 'pending')
          .eq('type', 'refund');
        
        return {
          primary: todayOrders || 0,
          secondary: 92, // 模拟收款率
          pending: pendingRefunds || 0,
          primaryLabel: '今日收款',
          secondaryLabel: '回款率',
          pendingLabel: '待退款'
        };
      }
      
      case 'service': {
        const { count: todayHandled } = await supabase
          .from('after_sales_requests')
          .select('*', { count: 'exact', head: true })
          .gte('updated_at', today.toISOString())
          .in('status', ['approved', 'rejected', 'completed']);
        
        const { count: pending } = await supabase
          .from('after_sales_requests')
          .select('*', { count: 'exact', head: true })
          .eq('status', 'pending');
        
        return {
          primary: todayHandled || 0,
          secondary: 85, // 模拟解决率
          pending: pending || 0,
          primaryLabel: '今日处理',
          secondaryLabel: '解决率',
          pendingLabel: '待处理'
        };
      }
      
      case 'manager':
      default: {
        const { count: todayOrders } = await supabase
          .from('orders')
          .select('*', { count: 'exact', head: true })
          .gte('created_at', today.toISOString());
        
        const { count: pendingTotal } = await supabase
          .from('after_sales_requests')
          .select('*', { count: 'exact', head: true })
          .eq('status', 'pending');
        
        return {
          primary: todayOrders || 0,
          secondary: 88, // 模拟运营效率
          pending: pendingTotal || 0,
          primaryLabel: '今日订单',
          secondaryLabel: '运营效率',
          pendingLabel: '待处理'
        };
      }
    }
  };
};

export function GenericAgentDashboard({ 
  agentType, 
  onSettingsClick, 
  compact = false 
}: GenericAgentDashboardProps) {
  const [status, setStatus] = useState<'online' | 'busy' | 'offline'>('online');
  const [metrics, setMetrics] = useState<AgentMetrics>({
    primary: 0,
    secondary: 0,
    pending: 0,
    primaryLabel: '',
    secondaryLabel: '',
    pendingLabel: ''
  });
  const [loading, setLoading] = useState(true);

  const agent = AI_AGENTS[agentType];

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

      const fetcher = getMetricsFetcher(agentType);
      const data = await fetcher();
      setMetrics(data);
    } catch (err) {
      console.error('Failed to fetch metrics:', err);
    } finally {
      setLoading(false);
    }
  };

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

  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={agent.avatar} alt={agent.name} />
          <AvatarFallback>{agent.emoji}</AvatarFallback>
        </Avatar>
        <div className="flex items-center gap-2">
          <span className="font-medium text-sm">{agent.name}</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>{metrics.primaryLabel}: <span className="text-foreground font-medium">{metrics.primary}</span></span>
          <span>{metrics.pendingLabel}: <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={agent.avatar} alt={agent.name} />
          <AvatarFallback>{agent.emoji}</AvatarFallback>
        </Avatar>
        <div>
          <div className="flex items-center gap-2">
            <span className="font-semibold">{agent.name}</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">{agent.role}</p>
        </div>
      </div>
      
      <div className="flex items-center gap-6">
        <div className="text-center">
          <div className="text-2xl font-bold">{metrics.primary}</div>
          <div className="text-xs text-muted-foreground">{metrics.primaryLabel}</div>
        </div>
        <div className="text-center">
          <div className="text-2xl font-bold">{metrics.secondary}%</div>
          <div className="text-xs text-muted-foreground">{metrics.secondaryLabel}</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">{metrics.pendingLabel}</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>
  );
}
