import { useEffect, useState, useCallback } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Progress } from "@/components/ui/progress";
import { ScrollArea } from "@/components/ui/scroll-area";
import { supabase } from "@/integrations/supabase/client";
import { toast } from "sonner";
import {
  LineChart,
  Line,
  BarChart,
  Bar,
  PieChart,
  Pie,
  AreaChart,
  Area,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
  Cell
} from "recharts";
import { 
  Package, 
  Users, 
  ShoppingCart, 
  TrendingUp,
  Bot,
  Lightbulb,
  Clock,
  CheckCircle2,
  Settings,
  Target,
  UsersRound,
  RefreshCw,
  LayoutGrid,
  Eye,
} from "lucide-react";
import { AgentSettingsDialog } from "./team";
import { UnifiedInsightFeed, UnifiedInsight, UnifiedApprovalCenter, CompletedTasksDialog } from "./shared";
import { useDashboardState } from "@/hooks/useDashboardState";
import { WidgetId, WIDGET_REGISTRY, getAllLayouts } from "@/ai/dashboardActions";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuCheckboxItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";

const COLORS = ['hsl(var(--chart-1))', 'hsl(var(--chart-2))', 'hsl(var(--chart-3))', 'hsl(var(--chart-4))', 'hsl(var(--chart-5))'];

interface DashboardStats {
  totalProducts: number;
  totalUsers: number;
  totalOrders: number;
  totalRevenue: number;
  salesTrend: Array<{ date: string; sales: number; orders: number }>;
  orderStatus: Array<{ name: string; value: number }>;
  categoryStats: Array<{ category: string; count: number }>;
  userGrowth: Array<{ month: string; users: number }>;
  loading: boolean;
}

// Agent 状态栏

// Agent 状态栏
function ManagerAgentStatusBar({ 
  onSettingsClick, 
  onTeamManageClick,
  onCompletedClick,
  completedCount,
  insightsCount,
  pendingCount 
}: { 
  onSettingsClick: () => void; 
  onTeamManageClick: () => void;
  onCompletedClick: () => void;
  completedCount: number;
  insightsCount: number;
  pendingCount: number;
}) {
  return (
    <div className="flex items-center gap-4 flex-wrap">
      <Card className="flex-shrink-0">
        <CardContent className="p-3 flex items-center gap-3">
          <div className="relative">
            <div className="h-10 w-10 rounded-full bg-primary/20 flex items-center justify-center">
              <Bot className="h-5 w-5 text-primary" />
            </div>
            <span className="absolute -bottom-0.5 -right-0.5 flex h-3.5 w-3.5">
              <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"></span>
              <span className="relative inline-flex rounded-full h-3.5 w-3.5 bg-emerald-500"></span>
            </span>
          </div>
          <div>
            <p className="text-xs text-muted-foreground">商城经理 · 小管</p>
            <div className="flex items-center gap-1.5">
              <span className="font-medium text-sm">运行中</span>
            </div>
          </div>
        </CardContent>
      </Card>
      
      <Card className="flex-shrink-0">
        <CardContent className="p-3 flex items-center gap-3">
          <div className="h-10 w-10 rounded-full bg-amber-500/20 flex items-center justify-center">
            <Lightbulb className="h-5 w-5 text-amber-500" />
          </div>
          <div>
            <p className="text-xs text-muted-foreground">今日洞察</p>
            <p className="font-semibold text-lg text-amber-600">{insightsCount}</p>
          </div>
        </CardContent>
      </Card>
      
      <Card className="flex-shrink-0">
        <CardContent className="p-3 flex items-center gap-3">
          <div className="h-10 w-10 rounded-full bg-destructive/20 flex items-center justify-center">
            <Clock className="h-5 w-5 text-destructive" />
          </div>
          <div>
            <p className="text-xs text-muted-foreground">待审批</p>
            <p className="font-semibold text-lg text-destructive">{pendingCount}</p>
          </div>
        </CardContent>
      </Card>
      
      <Card 
        className="flex-shrink-0 cursor-pointer hover:border-primary/50 transition-colors"
        onClick={onCompletedClick}
      >
        <CardContent className="p-3 flex items-center gap-3">
          <div className="h-10 w-10 rounded-full bg-emerald-500/20 flex items-center justify-center">
            <CheckCircle2 className="h-5 w-5 text-emerald-500" />
          </div>
          <div>
            <p className="text-xs text-muted-foreground">已协调完成</p>
            <p className="font-semibold text-lg text-emerald-600">{completedCount}</p>
          </div>
        </CardContent>
      </Card>
      
      <div className="flex-1 flex justify-end gap-2">
        <Button variant="outline" size="sm" onClick={onTeamManageClick}>
          <UsersRound className="h-4 w-4 mr-1" />
          团队管理
        </Button>
        <Button variant="outline" size="sm" onClick={onSettingsClick}>
          <Settings className="h-4 w-4 mr-1" />
          Agent设置
        </Button>
      </div>
    </div>
  );
}

// 商城目标卡片
function StoreGoalCard() {
  const [goal, setGoal] = useState<{
    title: string;
    description: string;
    target_value: number;
    current_value: number;
    deadline: string;
    priority: string;
    unit: string;
  } | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchGoal = async () => {
      try {
        const { data: goalData } = await supabase
          .from('goals')
          .select('*')
          .eq('agent_type', 'manager')
          .eq('status', 'active')
          .order('priority', { ascending: true })
          .limit(1)
          .single();

        if (goalData) {
          let currentValue = goalData.current_value;
          if (goalData.title.includes('GMV') || goalData.title.includes('销售')) {
            const startOfMonth = new Date(new Date().getFullYear(), new Date().getMonth(), 1).toISOString();
            const { data: orders } = await supabase
              .from('orders')
              .select('total_amount, status')
              .gte('created_at', startOfMonth)
              .neq('status', 'cancelled');
            
            currentValue = orders?.reduce((sum, o) => sum + (o.total_amount || 0), 0) || 0;
            
            await supabase
              .from('goals')
              .update({ current_value: currentValue })
              .eq('id', goalData.id);
          }
          
          setGoal({
            ...goalData,
            current_value: currentValue
          });
        }
      } catch (error) {
        console.error('获取店长目标失败:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchGoal();
  }, []);

  if (loading) {
    return (
      <Card className="bg-gradient-to-r from-primary/5 to-primary/10 border-primary/20">
        <CardContent className="p-4">
          <div className="animate-pulse space-y-3">
            <div className="h-10 bg-muted rounded w-3/4"></div>
            <div className="h-4 bg-muted rounded w-1/2"></div>
            <div className="h-2 bg-muted rounded"></div>
          </div>
        </CardContent>
      </Card>
    );
  }

  if (!goal) {
    return (
      <Card className="bg-gradient-to-r from-primary/5 to-primary/10 border-primary/20">
        <CardContent className="p-4">
          <div className="flex items-center gap-3">
            <div className="h-10 w-10 rounded-full bg-primary/20 flex items-center justify-center">
              <Target className="h-5 w-5 text-primary" />
            </div>
            <div>
              <p className="text-sm text-muted-foreground">本月经营目标</p>
              <p className="font-semibold text-muted-foreground">暂无设定目标</p>
            </div>
          </div>
        </CardContent>
      </Card>
    );
  }

  const progress = goal.target_value > 0 ? Math.min(100, Math.round((goal.current_value / goal.target_value) * 100)) : 0;
  const deadline = new Date(goal.deadline);
  const now = new Date();
  const daysLeft = Math.max(0, Math.ceil((deadline.getTime() - now.getTime()) / (1000 * 60 * 60 * 24)));

  const formatValue = (value: number, unit: string) => {
    if (unit === '元' || unit === '¥') {
      return `¥${value.toLocaleString()}`;
    }
    return `${value.toLocaleString()}${unit}`;
  };

  const getPriorityBadge = (priority: string) => {
    switch (priority) {
      case 'high':
        return <Badge className="text-xs bg-red-500/20 text-red-600">紧急</Badge>;
      case 'medium':
        return <Badge className="text-xs bg-amber-500/20 text-amber-600">重要</Badge>;
      default:
        return <Badge className="text-xs bg-blue-500/20 text-blue-600">普通</Badge>;
    }
  };
  
  return (
    <Card className="bg-gradient-to-r from-primary/5 to-primary/10 border-primary/20">
      <CardContent className="p-4">
        <div className="flex items-start justify-between mb-3">
          <div className="flex items-center gap-3">
            <div className="h-10 w-10 rounded-full bg-primary/20 flex items-center justify-center">
              <Target className="h-5 w-5 text-primary" />
            </div>
            <div>
              <div className="flex items-center gap-2">
                <p className="text-sm text-muted-foreground">本月经营目标</p>
                {getPriorityBadge(goal.priority)}
              </div>
              <p className="font-semibold">{goal.title}</p>
            </div>
          </div>
          
          <div className="text-right">
            <div className="flex items-center gap-1 text-xs text-muted-foreground">
              <Clock className="h-3 w-3" />
              剩余 {daysLeft} 天
            </div>
          </div>
        </div>
        
        {goal.description && (
          <p className="text-sm text-muted-foreground mb-3">
            {goal.description}
          </p>
        )}
        
        <div className="space-y-2">
          <div className="flex items-center justify-between text-sm">
            <span className="text-muted-foreground">完成进度</span>
            <span className="font-medium">
              {formatValue(goal.current_value, goal.unit)} / {formatValue(goal.target_value, goal.unit)}
            </span>
          </div>
          <Progress value={progress} className="h-2" />
          <div className="flex items-center justify-between text-xs text-muted-foreground">
            <span>各Agent协同执行中</span>
            <span>{progress}% 完成</span>
          </div>
        </div>
      </CardContent>
    </Card>
  );
}

// 布局控制器组件
function LayoutController({ 
  dashboardState 
}: { 
  dashboardState: ReturnType<typeof useDashboardState>
}) {
  const { state, setLayout, toggleWidget, resetToDefault } = dashboardState;
  const layouts = getAllLayouts();
  const allWidgets = Object.values(WIDGET_REGISTRY);
  
  return (
    <div className="flex items-center gap-2">
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button variant="outline" size="sm">
            <LayoutGrid className="h-4 w-4 mr-1" />
            布局
            <Badge variant="secondary" className="ml-2 text-xs">
              {state.layout === 'custom' ? '自定义' : layouts.find(l => l.id === state.layout)?.name}
            </Badge>
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end" className="w-56">
          <DropdownMenuLabel>切换布局</DropdownMenuLabel>
          <DropdownMenuSeparator />
          {layouts.map(layout => (
            <DropdownMenuItem 
              key={layout.id}
              onClick={() => setLayout(layout.id)}
              className={state.layout === layout.id ? 'bg-accent' : ''}
            >
              {layout.name}
              <span className="ml-auto text-xs text-muted-foreground">
                {layout.widgets.length}组件
              </span>
            </DropdownMenuItem>
          ))}
          <DropdownMenuSeparator />
          <DropdownMenuItem onClick={resetToDefault}>
            <RefreshCw className="h-4 w-4 mr-2" />
            重置为默认
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
      
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button variant="outline" size="sm">
            <Eye className="h-4 w-4 mr-1" />
            组件
            <Badge variant="secondary" className="ml-2 text-xs">
              {state.visibleWidgets.length}/{allWidgets.length}
            </Badge>
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end" className="w-56">
          <DropdownMenuLabel>显示/隐藏组件</DropdownMenuLabel>
          <DropdownMenuSeparator />
          {allWidgets.map(widget => (
            <DropdownMenuCheckboxItem
              key={widget.id}
              checked={state.visibleWidgets.includes(widget.id)}
              onCheckedChange={() => toggleWidget(widget.id)}
            >
              {widget.nameCN}
            </DropdownMenuCheckboxItem>
          ))}
        </DropdownMenuContent>
      </DropdownMenu>
    </div>
  );
}

interface AdminDashboardProps {
  onNavigate?: (tab: string) => void;
}

export function AdminDashboard({ onNavigate }: AdminDashboardProps) {
  const dashboardState = useDashboardState();
  const { state, isWidgetVisible, isFocused, refreshSignal } = dashboardState;
  
  const [stats, setStats] = useState<DashboardStats>({
    totalProducts: 0,
    totalUsers: 0,
    totalOrders: 0,
    totalRevenue: 0,
    salesTrend: [],
    orderStatus: [],
    categoryStats: [],
    userGrowth: [],
    loading: true
  });
  const [settingsOpen, setSettingsOpen] = useState(false);
  const [settingsAgentType, setSettingsAgentType] = useState<string | undefined>(undefined);
  const [insights, setInsights] = useState<UnifiedInsight[]>([]);
  const [insightsLoading, setInsightsLoading] = useState(false);
  const [completedDialogOpen, setCompletedDialogOpen] = useState(false);
  const [completedCount, setCompletedCount] = useState(0);
  const [pendingCount, setPendingCount] = useState(0);

  // 获取已完成和待审批数量
  useEffect(() => {
    const fetchCounts = async () => {
      try {
        const [
          { count: afterSalesApproved }, 
          { count: campaignsApproved },
          { count: afterSalesPending },
          { count: campaignsPending }
        ] = await Promise.all([
          supabase
            .from('after_sales_requests')
            .select('*', { count: 'exact', head: true })
            .in('status', ['approved', 'rejected']),
          supabase
            .from('marketing_campaigns')
            .select('*', { count: 'exact', head: true })
            .in('status', ['approved', 'rejected']),
          supabase
            .from('after_sales_requests')
            .select('*', { count: 'exact', head: true })
            .eq('status', 'pending'),
          supabase
            .from('marketing_campaigns')
            .select('*', { count: 'exact', head: true })
            .eq('status', 'pending')
        ]);
        setCompletedCount((afterSalesApproved || 0) + (campaignsApproved || 0));
        setPendingCount((afterSalesPending || 0) + (campaignsPending || 0));
      } catch (error) {
        console.error('获取统计数量失败:', error);
      }
    };
    fetchCounts();
  }, []);

  const quickActions = [
    { title: "商品管理", description: "添加、编辑商品信息", icon: Package, action: "products", color: "text-blue-600" },
    { title: "用户管理", description: "查看和管理用户", icon: Users, action: "users", color: "text-green-600" },
    { title: "订单处理", description: "处理待发货订单", icon: ShoppingCart, action: "orders", color: "text-purple-600" },
    { title: "营销活动", description: "管理营销活动", icon: TrendingUp, action: "marketing", color: "text-orange-600" },
  ];

  const fetchInsights = useCallback(async () => {
    setInsightsLoading(true);
    try {
      const { data: { session } } = await supabase.auth.getSession();
      if (!session) {
        toast.error("请先登录");
        return;
      }

      const { data, error } = await supabase.functions.invoke("manager-insights", {
        headers: { Authorization: `Bearer ${session.access_token}` },
      });

      if (error) throw error;
      if (data?.insights) {
        setInsights(data.insights);
        toast.success("经营洞察已更新");
      }
    } catch (error) {
      console.error("获取经营洞察失败:", error);
      toast.error("获取经营洞察失败");
    } finally {
      setInsightsLoading(false);
    }
  }, []);

  // 监听刷新信号
  useEffect(() => {
    if (refreshSignal.insight_feed) {
      fetchInsights();
    }
  }, [refreshSignal.insight_feed, fetchInsights]);

  useEffect(() => {
    fetchDashboardData();
    fetchInsights();
  }, [fetchInsights]);

  const fetchDashboardData = async () => {
    try {
      const { count: productsCount } = await supabase.from('products').select('*', { count: 'exact', head: true }).eq('is_active', true);
      const { count: usersCount } = await supabase.from('profiles').select('*', { count: 'exact', head: true });
      const { count: ordersCount } = await supabase.from('orders').select('*', { count: 'exact', head: true });
      const { data: revenueData } = await supabase.from('orders').select('total_amount').not('status', 'eq', 'cancelled');

      const totalRevenue = revenueData?.reduce((sum, order) => sum + (order.total_amount || 0), 0) || 0;

      const { data: recentOrders } = await supabase.from('orders')
        .select('created_at, total_amount, status')
        .gte('created_at', new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString())
        .order('created_at', { ascending: true });

      const salesByDate = new Map<string, { sales: number; orders: number }>();
      recentOrders?.forEach(order => {
        const date = new Date(order.created_at).toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' });
        const current = salesByDate.get(date) || { sales: 0, orders: 0 };
        if (order.status !== 'cancelled') {
          current.sales += order.total_amount || 0;
          current.orders += 1;
        }
        salesByDate.set(date, current);
      });

      const salesTrend = Array.from(salesByDate.entries()).map(([date, data]) => ({
        date, sales: Math.round(data.sales), orders: data.orders
      }));

      const { data: ordersByStatus } = await supabase.from('orders').select('status');
      const statusMap = new Map<string, number>();
      ordersByStatus?.forEach(order => {
        const statusName = getStatusName(order.status);
        statusMap.set(statusName, (statusMap.get(statusName) || 0) + 1);
      });
      const orderStatus = Array.from(statusMap.entries()).map(([name, value]) => ({ name, value }));

      const { data: products } = await supabase.from('products').select('category').eq('is_active', true);
      const categoryMap = new Map<string, number>();
      products?.forEach(product => {
        const category = product.category || '未分类';
        categoryMap.set(category, (categoryMap.get(category) || 0) + 1);
      });
      const categoryStats = Array.from(categoryMap.entries())
        .map(([category, count]) => ({ category, count }))
        .sort((a, b) => b.count - a.count)
        .slice(0, 8);

      const { data: usersByMonth } = await supabase.from('profiles')
        .select('created_at')
        .gte('created_at', new Date(Date.now() - 180 * 24 * 60 * 60 * 1000).toISOString())
        .order('created_at', { ascending: true });

      const monthMap = new Map<string, number>();
      usersByMonth?.forEach(user => {
        const month = new Date(user.created_at).toLocaleDateString('zh-CN', { year: 'numeric', month: 'short' });
        monthMap.set(month, (monthMap.get(month) || 0) + 1);
      });

      let cumulative = 0;
      const userGrowth = Array.from(monthMap.entries()).map(([month, count]) => {
        cumulative += count;
        return { month, users: cumulative };
      });

      setStats({
        totalProducts: productsCount || 0,
        totalUsers: usersCount || 0,
        totalOrders: ordersCount || 0,
        totalRevenue,
        salesTrend,
        orderStatus,
        categoryStats,
        userGrowth,
        loading: false
      });
    } catch (error) {
      console.error('获取仪表盘数据失败:', error);
      setStats(prev => ({ ...prev, loading: false }));
    }
  };

  const getStatusName = (status: string): string => {
    const statusNames: { [key: string]: string } = {
      'pending': '待处理', 'confirmed': '已确认', 'shipped': '已发货',
      'delivered': '已送达', 'cancelled': '已取消'
    };
    return statusNames[status] || status;
  };

  const getInsightTargetTab = (insight: UnifiedInsight): string | null => {
    const { title, description, agent } = insight;
    const content = `${title} ${description}`.toLowerCase();
    
    if (agent) {
      switch (agent) {
        case '小品': return 'products';
        case '小营': return 'marketing';
        case '小服': return 'aftersales';
        case '小财': return 'transactions';
      }
    }
    
    if (content.includes('库存') || content.includes('商品')) return 'products';
    if (content.includes('订单') || content.includes('发货')) return 'transactions';
    if (content.includes('营销') || content.includes('促销')) return 'marketing';
    if (content.includes('售后') || content.includes('退款')) return 'aftersales';
    
    return null;
  };

  const handleInsightClick = (insight: UnifiedInsight) => {
    const targetTab = getInsightTargetTab(insight);
    if (targetTab && onNavigate) onNavigate(targetTab);
  };

  if (stats.loading) {
    return (
      <div className="flex items-center justify-center h-96">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
      </div>
    );
  }

  // 聚焦模式：只显示聚焦的组件
  const renderFocusedMode = () => {
    if (!state.focusedWidget) return null;
    
    return (
      <div className="space-y-4">
        <div className="flex items-center justify-between">
          <h2 className="text-lg font-semibold">
            聚焦: {WIDGET_REGISTRY[state.focusedWidget]?.nameCN}
          </h2>
          <Button variant="outline" size="sm" onClick={() => dashboardState.focusWidget(null)}>
            退出聚焦
          </Button>
        </div>
        {renderWidget(state.focusedWidget, true)}
      </div>
    );
  };

  // 渲染单个组件
  const renderWidget = (widgetId: WidgetId, expanded = false) => {
    const className = expanded ? "col-span-full" : "";
    
    switch (widgetId) {
      case 'agent_status':
        return (
          <ManagerAgentStatusBar 
            key={widgetId}
            onSettingsClick={() => { setSettingsAgentType('manager'); setSettingsOpen(true); }}
            onTeamManageClick={() => { setSettingsAgentType(undefined); setSettingsOpen(true); }}
            onCompletedClick={() => setCompletedDialogOpen(true)}
            completedCount={completedCount}
            insightsCount={insights.length}
            pendingCount={pendingCount}
          />
        );
      
      case 'store_goal':
        return <StoreGoalCard key={widgetId} />;
      
      case 'insight_feed':
        return (
          <UnifiedInsightFeed
            key={widgetId}
            title="经营洞察"
            insights={insights}
            loading={insightsLoading}
            height={expanded ? "400px" : "280px"}
            onRefresh={fetchInsights}
            onClick={handleInsightClick}
          />
        );
      
      case 'pending_approvals':
        return (
          <UnifiedApprovalCenter 
            key={widgetId}
            onNavigate={onNavigate}
            height={expanded ? "400px" : "280px"}
            compact={!expanded}
          />
        );
      
      case 'quick_actions':
        return onNavigate ? (
          <Card key={widgetId} className={className}>
            <CardHeader className="pb-3">
              <CardTitle className="text-base">快捷操作</CardTitle>
              <CardDescription>快速访问常用功能</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="grid gap-3 md:grid-cols-2 lg:grid-cols-4">
                {quickActions.map((action) => (
                  <Button key={action.action} variant="outline" className="h-auto flex flex-col items-start p-3 hover:bg-muted/50" onClick={() => onNavigate(action.action)}>
                    <div className="flex items-center gap-2 mb-1">
                      <action.icon className={`h-4 w-4 ${action.color}`} />
                      <span className="font-medium text-sm">{action.title}</span>
                    </div>
                    <p className="text-xs text-muted-foreground text-left">{action.description}</p>
                  </Button>
                ))}
              </div>
            </CardContent>
          </Card>
        ) : null;
      
      case 'stats_cards':
        return (
          <div key={widgetId} className={`grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 ${className}`}>
            <Card className="overflow-hidden border-l-4 border-l-primary hover:shadow-lg transition-shadow">
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">总商品数</CardTitle>
                <Package className="h-5 w-5 text-primary" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold text-foreground">{stats.totalProducts}</div>
                <p className="text-xs text-muted-foreground mt-1">活跃商品总数</p>
              </CardContent>
            </Card>
            <Card className="overflow-hidden border-l-4 border-l-primary hover:shadow-lg transition-shadow">
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">用户总数</CardTitle>
                <Users className="h-5 w-5 text-primary" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold text-foreground">{stats.totalUsers}</div>
                <p className="text-xs text-muted-foreground mt-1">已注册用户</p>
              </CardContent>
            </Card>
            <Card className="overflow-hidden border-l-4 border-l-primary hover:shadow-lg transition-shadow">
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">订单总数</CardTitle>
                <ShoppingCart className="h-5 w-5 text-primary" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold text-foreground">{stats.totalOrders}</div>
                <p className="text-xs text-muted-foreground mt-1">全部订单</p>
              </CardContent>
            </Card>
            <Card className="overflow-hidden border-l-4 border-l-primary hover:shadow-lg transition-shadow">
              <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                <CardTitle className="text-sm font-medium">总销售额</CardTitle>
                <TrendingUp className="h-5 w-5 text-primary" />
              </CardHeader>
              <CardContent>
                <div className="text-2xl font-bold text-foreground">¥{stats.totalRevenue.toLocaleString()}</div>
                <p className="text-xs text-muted-foreground mt-1">累计销售收入</p>
              </CardContent>
            </Card>
          </div>
        );
      
      case 'sales_trend':
        return (
          <Card key={widgetId} className={`hover:shadow-lg transition-shadow ${className}`}>
            <CardHeader>
              <CardTitle className="text-base">近7日销售趋势</CardTitle>
              <CardDescription>销售额与订单数量变化</CardDescription>
            </CardHeader>
            <CardContent>
              <ResponsiveContainer width="100%" height={expanded ? 350 : 250}>
                <LineChart data={stats.salesTrend}>
                  <CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" />
                  <XAxis dataKey="date" stroke="hsl(var(--muted-foreground))" fontSize={12} />
                  <YAxis stroke="hsl(var(--muted-foreground))" fontSize={12} />
                  <Tooltip contentStyle={{ backgroundColor: 'hsl(var(--card))', border: '1px solid hsl(var(--border))', borderRadius: '8px' }} />
                  <Legend />
                  <Line type="monotone" dataKey="sales" stroke="hsl(var(--primary))" name="销售额(¥)" strokeWidth={2} dot={{ fill: 'hsl(var(--primary))' }} />
                  <Line type="monotone" dataKey="orders" stroke="hsl(var(--chart-2))" name="订单数" strokeWidth={2} dot={{ fill: 'hsl(var(--chart-2))' }} />
                </LineChart>
              </ResponsiveContainer>
            </CardContent>
          </Card>
        );
      
      case 'order_status':
        return (
          <Card key={widgetId} className={`hover:shadow-lg transition-shadow ${className}`}>
            <CardHeader>
              <CardTitle className="text-base">订单状态分布</CardTitle>
              <CardDescription>各状态订单占比</CardDescription>
            </CardHeader>
            <CardContent>
              <ResponsiveContainer width="100%" height={expanded ? 350 : 250}>
                <PieChart>
                  <Pie data={stats.orderStatus} cx="50%" cy="50%" labelLine={false} label={({ name, percent }) => `${name}: ${(percent * 100).toFixed(0)}%`} outerRadius={80} fill="hsl(var(--primary))" dataKey="value">
                    {stats.orderStatus.map((_, index) => (<Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />))}
                  </Pie>
                  <Tooltip contentStyle={{ backgroundColor: 'hsl(var(--card))', border: '1px solid hsl(var(--border))', borderRadius: '8px' }} />
                </PieChart>
              </ResponsiveContainer>
            </CardContent>
          </Card>
        );
      
      case 'category_stats':
        return (
          <Card key={widgetId} className={`hover:shadow-lg transition-shadow ${className}`}>
            <CardHeader>
              <CardTitle className="text-base">商品分类统计</CardTitle>
              <CardDescription>各类别商品数量</CardDescription>
            </CardHeader>
            <CardContent>
              <ResponsiveContainer width="100%" height={expanded ? 350 : 250}>
                <BarChart data={stats.categoryStats}>
                  <CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" />
                  <XAxis dataKey="category" stroke="hsl(var(--muted-foreground))" fontSize={12} angle={-45} textAnchor="end" height={80} />
                  <YAxis stroke="hsl(var(--muted-foreground))" fontSize={12} />
                  <Tooltip contentStyle={{ backgroundColor: 'hsl(var(--card))', border: '1px solid hsl(var(--border))', borderRadius: '8px' }} />
                  <Bar dataKey="count" fill="hsl(var(--primary))" name="商品数量" radius={[8, 8, 0, 0]} />
                </BarChart>
              </ResponsiveContainer>
            </CardContent>
          </Card>
        );
      
      case 'user_growth':
        return (
          <Card key={widgetId} className={`hover:shadow-lg transition-shadow ${className}`}>
            <CardHeader>
              <CardTitle className="text-base">用户增长趋势</CardTitle>
              <CardDescription>累计注册用户数</CardDescription>
            </CardHeader>
            <CardContent>
              <ResponsiveContainer width="100%" height={expanded ? 350 : 250}>
                <AreaChart data={stats.userGrowth}>
                  <defs>
                    <linearGradient id="colorUsers" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="5%" stopColor="hsl(var(--primary))" stopOpacity={0.8}/>
                      <stop offset="95%" stopColor="hsl(var(--primary))" stopOpacity={0}/>
                    </linearGradient>
                  </defs>
                  <CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" />
                  <XAxis dataKey="month" stroke="hsl(var(--muted-foreground))" fontSize={12} />
                  <YAxis stroke="hsl(var(--muted-foreground))" fontSize={12} />
                  <Tooltip contentStyle={{ backgroundColor: 'hsl(var(--card))', border: '1px solid hsl(var(--border))', borderRadius: '8px' }} />
                  <Area type="monotone" dataKey="users" stroke="hsl(var(--primary))" fillOpacity={1} fill="url(#colorUsers)" name="用户数" />
                </AreaChart>
              </ResponsiveContainer>
            </CardContent>
          </Card>
        );
      
      default:
        return null;
    }
  };

  // 聚焦模式
  if (state.focusedWidget) {
    return (
      <div className="space-y-6">
        <AgentSettingsDialog open={settingsOpen} onOpenChange={setSettingsOpen} agentType={settingsAgentType} />
        {renderFocusedMode()}
      </div>
    );
  }

  // 正常模式：根据 visibleWidgets 渲染
  return (
    <div className="space-y-6">
      <AgentSettingsDialog open={settingsOpen} onOpenChange={setSettingsOpen} agentType={settingsAgentType} />
      <CompletedTasksDialog open={completedDialogOpen} onOpenChange={setCompletedDialogOpen} />
      
      {/* 布局控制器 */}
      <div className="flex items-center justify-between">
        <h1 className="text-xl font-semibold">店长工作台</h1>
        <LayoutController dashboardState={dashboardState} />
      </div>

      {/* Agent 状态栏 */}
      {isWidgetVisible('agent_status') && renderWidget('agent_status')}

      {/* 店铺目标 */}
      {isWidgetVisible('store_goal') && renderWidget('store_goal')}

      {/* 洞察和待审批 */}
      {(isWidgetVisible('insight_feed') || isWidgetVisible('pending_approvals')) && (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {isWidgetVisible('insight_feed') && renderWidget('insight_feed')}
          {isWidgetVisible('pending_approvals') && renderWidget('pending_approvals')}
        </div>
      )}

      {/* 快捷操作 */}
      {isWidgetVisible('quick_actions') && renderWidget('quick_actions')}

      {/* 统计卡片 */}
      {isWidgetVisible('stats_cards') && renderWidget('stats_cards')}

      {/* 图表区域 */}
      {(isWidgetVisible('sales_trend') || isWidgetVisible('order_status') || isWidgetVisible('category_stats') || isWidgetVisible('user_growth')) && (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {isWidgetVisible('sales_trend') && renderWidget('sales_trend')}
          {isWidgetVisible('order_status') && renderWidget('order_status')}
          {isWidgetVisible('category_stats') && renderWidget('category_stats')}
          {isWidgetVisible('user_growth') && renderWidget('user_growth')}
        </div>
      )}
    </div>
  );
}
