import { useState, useMemo, useEffect, useCallback } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Progress } from "@/components/ui/progress";
import { 
  Bot, Package, TrendingDown, TrendingUp, AlertTriangle, 
  CheckCircle, Clock, Lightbulb, ArrowRight, Settings,
  BarChart3, RefreshCw
} from "lucide-react";
import { AgentSettingsDialog } from "../team";
import { formatDistanceToNow } from "date-fns";
import { zhCN } from "date-fns/locale";
import { supabase } from "@/integrations/supabase/client";
import { toast } from "sonner";
import { UnifiedInsightFeed, UnifiedInsight, CompletedTasksDialog } from "../shared";
import { useQuery } from "@tanstack/react-query";

// 商品经理目标接口
interface ProductManagerGoal {
  id: string;
  title: string;
  description: string;
  targetValue: number;
  currentValue: number;
  unit: string;
  deadline: string;
  priority: 'high' | 'medium' | 'low';
}

// 待处理商品操作
interface PendingProductAction {
  id: string;
  type: 'restock' | 'price_adjust' | 'discontinue' | 'promote';
  productName: string;
  productId: string;
  reason: string;
  suggestedValue?: string;
  aiConfidence: number;
  createdAt: string;
}

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

// Mock data for goal demonstration
const mockGoal: ProductManagerGoal = {
  id: "1",
  title: "本月库存周转率",
  description: "提升商品库存周转效率",
  targetValue: 4.5,
  currentValue: 3.8,
  unit: "次/月",
  deadline: new Date(Date.now() + 18 * 24 * 60 * 60 * 1000).toISOString(),
  priority: "high",
};

const impactConfig: Record<string, { label: string; color: string }> = {
  high: { label: "高", color: "bg-destructive/10 text-destructive" },
  medium: { label: "中", color: "bg-amber-500/10 text-amber-600" },
  low: { label: "低", color: "bg-muted text-muted-foreground" },
};

const actionTypeConfig: Record<string, { label: string; color: string }> = {
  restock: { label: "补货", color: "bg-chart-2" },
  price_adjust: { label: "调价", color: "bg-amber-500" },
  discontinue: { label: "下架", color: "bg-destructive" },
  promote: { label: "推广", color: "bg-success" },
};

export function ProductAICockpit({ onNavigateToProducts, onNavigate }: ProductAICockpitProps) {
  const [insights, setInsights] = useState<UnifiedInsight[]>([]);
  const [goal] = useState<ProductManagerGoal>(mockGoal);
  const [agentSettingsOpen, setAgentSettingsOpen] = useState(false);
  const [executedDialogOpen, setExecutedDialogOpen] = useState(false);
  const [loading, setLoading] = useState(false);

  // 从数据库获取待处理商品操作（低库存、滞销商品）
  const { data: pendingActions = [] } = useQuery({
    queryKey: ['product-pending-actions'],
    queryFn: async () => {
      // 获取低库存商品（库存 <= 10）
      const { data: lowStockProducts, error: lowStockError } = await supabase
        .from('products')
        .select('id, name, stock_quantity, monthly_sales, price')
        .lte('stock_quantity', 10)
        .eq('is_active', true)
        .order('stock_quantity', { ascending: true })
        .limit(5);

      if (lowStockError) throw lowStockError;

      // 获取滞销商品（月销量 < 5）
      const { data: slowMovingProducts, error: slowError } = await supabase
        .from('products')
        .select('id, name, stock_quantity, monthly_sales, price')
        .lt('monthly_sales', 5)
        .gt('stock_quantity', 20)
        .eq('is_active', true)
        .order('monthly_sales', { ascending: true })
        .limit(5);

      if (slowError) throw slowError;

      const actions: PendingProductAction[] = [];

      // 低库存商品转换为补货建议
      (lowStockProducts || []).forEach(product => {
        actions.push({
          id: `restock-${product.id}`,
          type: 'restock',
          productName: product.name,
          productId: product.id,
          reason: `库存仅剩 ${product.stock_quantity} 件，建议补货`,
          suggestedValue: `补货 ${Math.max(50, (product.monthly_sales || 10) * 2)} 件`,
          aiConfidence: 90 + Math.floor(Math.random() * 8),
          createdAt: new Date().toISOString()
        });
      });

      // 滞销商品转换为调价建议
      (slowMovingProducts || []).forEach(product => {
        actions.push({
          id: `price-${product.id}`,
          type: 'price_adjust',
          productName: product.name,
          productId: product.id,
          reason: `月销量仅 ${product.monthly_sales || 0} 件，库存 ${product.stock_quantity} 件，建议促销`,
          suggestedValue: `降价 10-15%`,
          aiConfidence: 75 + Math.floor(Math.random() * 10),
          createdAt: new Date().toISOString()
        });
      });

      return actions;
    }
  });

  // 获取商品统计
  const { data: productStats } = useQuery({
    queryKey: ['product-stats'],
    queryFn: async () => {
      const { data, error } = await supabase
        .from('products')
        .select('id, stock_quantity, monthly_sales, is_active');

      if (error) throw error;

      const activeProducts = (data || []).filter(p => p.is_active);
      const lowStockCount = activeProducts.filter(p => p.stock_quantity <= 10).length;
      const slowMovingCount = activeProducts.filter(p => (p.monthly_sales || 0) < 5 && p.stock_quantity > 20).length;

      return {
        totalActive: activeProducts.length,
        lowStockCount,
        slowMovingCount
      };
    }
  });

  // 获取AI洞察
  const fetchInsights = useCallback(async () => {
    setLoading(true);
    try {
      const { data: { session } } = await supabase.auth.getSession();
      if (!session) {
        toast.error("请先登录");
        return;
      }

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

      if (error) throw error;
      
      if (data?.success && data?.insights?.length > 0) {
        setInsights(data.insights);
        toast.success(`AI生成了 ${data.insights.length} 条商品洞察`);
      } else if (data?.error) {
        console.error('Insights error:', data.error);
        toast.error(`获取洞察失败: ${data.error}`);
      }
    } catch (error) {
      console.error('Failed to fetch insights:', error);
      toast.error("获取AI洞察失败");
    } finally {
      setLoading(false);
    }
  }, []);

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

  const stats = useMemo(() => ({
    totalInsights: insights.length,
    highImpactInsights: insights.filter(i => i.priority === 'high').length,
    pendingActions: pendingActions.length,
  }), [insights, pendingActions]);

  const goalProgress = (goal.currentValue / goal.targetValue) * 100;
  const daysLeft = Math.ceil((new Date(goal.deadline).getTime() - Date.now()) / (1000 * 60 * 60 * 24));

  // 根据洞察内容确定跳转目标
  const getInsightTargetTab = (insight: UnifiedInsight): string | null => {
    const { title, description } = insight;
    const content = `${title} ${description}`.toLowerCase();
    
    if (content.includes('订单') || content.includes('发货') || content.includes('物流') || content.includes('营收')) {
      return 'transactions';
    }
    if (content.includes('退款') || content.includes('售后') || content.includes('客服')) {
      return 'aftersales';
    }
    if (content.includes('营销') || content.includes('活动') || content.includes('优惠')) {
      return 'marketing';
    }
    return 'products'; // 商品相关默认留在商品部
  };

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

  const handleInsightAction = (insightId: string, action: string) => {
    toast.info(`执行操作: ${action}`);
  };

  const handleApproveAction = (action: PendingProductAction) => {
    console.log("Approve action:", action);
  };

  const handleRejectAction = (action: PendingProductAction) => {
    console.log("Reject action:", action);
  };

  return (
    <div className="space-y-6">
      {/* 已处理任务弹窗 */}
      <CompletedTasksDialog 
        open={executedDialogOpen} 
        onOpenChange={setExecutedDialogOpen}
      />
      {/* 商品经理目标卡片 */}
      <Card className="bg-gradient-to-br from-chart-3/10 to-chart-3/5 border-chart-3/20">
        <CardContent className="p-4">
          <div className="flex items-start justify-between">
            <div className="flex-1">
              <div className="flex items-center gap-2 mb-2">
                <Badge variant="outline" className="text-chart-3 border-chart-3">
                  商品经理目标
                </Badge>
                <Badge className={`${impactConfig[goal.priority].color}`}>
                  {goal.priority === 'high' ? '高优先级' : goal.priority === 'medium' ? '中优先级' : '低优先级'}
                </Badge>
              </div>
              <h3 className="font-semibold text-lg">{goal.title}</h3>
              <p className="text-sm text-muted-foreground mt-1">{goal.description}</p>
              <div className="mt-4 space-y-2">
                <div className="flex justify-between text-sm">
                  <span>当前: {goal.currentValue} {goal.unit}</span>
                  <span>目标: {goal.targetValue} {goal.unit}</span>
                </div>
                <Progress value={goalProgress} className="h-2" />
                <p className="text-xs text-muted-foreground">
                  距离截止还有 {daysLeft} 天
                </p>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Agent 状态栏 - 与其他部门保持一致的卡片式布局 */}
      <div className="flex items-center gap-4 flex-wrap">
        {/* Agent状态 */}
        <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-chart-3/20 flex items-center justify-center">
                <Package className="h-5 w-5 text-chart-3" />
              </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">商品AI · 小品</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">{stats.totalInsights}</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">{stats.pendingActions}</p>
            </div>
          </CardContent>
        </Card>
        
        {/* 高优先级 */}
        <Card 
          className="flex-shrink-0 cursor-pointer hover:border-primary/50 transition-colors"
          onClick={() => setExecutedDialogOpen(true)}
        >
          <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">
              <CheckCircle 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">{stats.highImpactInsights}</p>
            </div>
          </CardContent>
        </Card>
        
        {/* 操作按钮 */}
        <div className="flex-1 flex justify-end">
          <Button variant="outline" size="sm" onClick={() => setAgentSettingsOpen(true)}>
            <Settings className="h-4 w-4 mr-1" />
            Agent设置
          </Button>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* 商品洞察流 - 使用统一组件 */}
        <UnifiedInsightFeed
          title="商品洞察"
          insights={insights}
          loading={loading}
          height="280px"
          onAction={handleInsightAction}
          onClick={handleInsightClick}
          onRefresh={fetchInsights}
        />

        {/* 待处理操作 */}
        <Card>
          <CardHeader className="pb-3">
            <div className="flex items-center justify-between">
              <CardTitle className="flex items-center gap-2 text-base">
                <Clock className="h-4 w-4 text-amber-500" />
                AI建议操作
                <Badge variant="secondary" className="ml-1">{pendingActions.length}</Badge>
              </CardTitle>
            </div>
          </CardHeader>
          <CardContent>
            <ScrollArea className="h-[350px] pr-4">
              {pendingActions.length === 0 ? (
                <div className="flex flex-col items-center justify-center py-12 text-muted-foreground">
                  <CheckCircle className="h-12 w-12 mb-3 opacity-20" />
                  <p>暂无待处理操作</p>
                </div>
              ) : (
                <div className="space-y-3">
                  {pendingActions.map((action) => (
                    <Card key={action.id} className="p-3">
                      <div className="space-y-2">
                        <div className="flex items-start justify-between">
                          <div className="flex items-center gap-2">
                            <Badge className={`${actionTypeConfig[action.type].color} text-white`}>
                              {actionTypeConfig[action.type].label}
                            </Badge>
                            <span className="font-medium text-sm truncate max-w-[150px]">
                              {action.productName}
                            </span>
                          </div>
                          <div className="flex items-center gap-1 text-xs text-muted-foreground">
                            <Bot className="h-3 w-3" />
                            {action.aiConfidence}%
                          </div>
                        </div>
                        <p className="text-xs text-muted-foreground">{action.reason}</p>
                        {action.suggestedValue && (
                          <p className="text-xs font-medium text-chart-3">
                            建议: {action.suggestedValue}
                          </p>
                        )}
                        <div className="flex items-center justify-between pt-1">
                          <span className="text-xs text-muted-foreground">
                            {formatDistanceToNow(new Date(action.createdAt), { addSuffix: true, locale: zhCN })}
                          </span>
                          <div className="flex gap-1">
                            <Button 
                              variant="ghost" 
                              size="sm" 
                              className="h-6 text-xs"
                              onClick={() => handleRejectAction(action)}
                            >
                              忽略
                            </Button>
                            <Button 
                              size="sm" 
                              className="h-6 text-xs"
                              onClick={() => handleApproveAction(action)}
                            >
                              执行
                            </Button>
                          </div>
                        </div>
                      </div>
                    </Card>
                  ))}
                </div>
              )}
            </ScrollArea>
          </CardContent>
        </Card>
      </div>

      {/* 快捷数据概览 */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <Card className="p-4">
          <div className="flex items-center gap-3">
            <div className="h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center">
              <Package className="h-5 w-5 text-primary" />
            </div>
            <div>
              <p className="text-2xl font-bold">{productStats?.totalActive || 0}</p>
              <p className="text-xs text-muted-foreground">在售商品</p>
            </div>
          </div>
        </Card>
        <Card className="p-4">
          <div className="flex items-center gap-3">
            <div className="h-10 w-10 rounded-lg bg-destructive/10 flex items-center justify-center">
              <AlertTriangle className="h-5 w-5 text-destructive" />
            </div>
            <div>
              <p className="text-2xl font-bold">{productStats?.lowStockCount || 0}</p>
              <p className="text-xs text-muted-foreground">库存预警</p>
            </div>
          </div>
        </Card>
        <Card className="p-4">
          <div className="flex items-center gap-3">
            <div className="h-10 w-10 rounded-lg bg-amber-500/10 flex items-center justify-center">
              <TrendingDown className="h-5 w-5 text-amber-500" />
            </div>
            <div>
              <p className="text-2xl font-bold">{productStats?.slowMovingCount || 0}</p>
              <p className="text-xs text-muted-foreground">滞销商品</p>
            </div>
          </div>
        </Card>
        <Card className="p-4">
          <div className="flex items-center gap-3">
            <div className="h-10 w-10 rounded-lg bg-success/10 flex items-center justify-center">
              <BarChart3 className="h-5 w-5 text-success" />
            </div>
            <div>
              <p className="text-2xl font-bold">3.8</p>
              <p className="text-xs text-muted-foreground">库存周转率</p>
            </div>
          </div>
        </Card>
      </div>

      <AgentSettingsDialog 
        open={agentSettingsOpen} 
        onOpenChange={setAgentSettingsOpen} 
        agentType="product"
      />
    </div>
  );
}
