import { useState, useMemo, useEffect, useCallback } from "react";
import { AgentStatusBar } from "./AgentStatusBar";
import { UnifiedInsightFeed, UnifiedInsight, CompletedTasksDialog } from "../shared";
import { PendingApprovals, PendingCampaign } from "./PendingApprovals";
import { ManagerGoalCard } from "./ManagerGoalCard";
import { toast } from "sonner";
import { AgentSettingsDialog } from "../team";
import { useGoals } from "@/hooks/useGoals";
import { supabase } from "@/integrations/supabase/client";
import { RefreshCw } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useQuery, useQueryClient } from "@tanstack/react-query";

interface AICockpitProps {
  onNavigateToCoupons?: () => void;
  onOpenSettings?: (agentType: string) => void;
  onNavigate?: (tab: string) => void;
}

export function AICockpit({ onNavigateToCoupons, onOpenSettings, onNavigate }: AICockpitProps) {
  const [insights, setInsights] = useState<UnifiedInsight[]>([]);
  const [settingsOpen, setSettingsOpen] = useState(false);
  const [executedDialogOpen, setExecutedDialogOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [lastUpdated, setLastUpdated] = useState<Date | null>(null);
  const queryClient = useQueryClient();
  
  // 使用真实目标数据
  const { primaryGoal, loading: goalLoading } = useGoals('marketing');

  // 从数据库获取待审批营销活动
  const { data: pendingCampaigns = [] } = useQuery({
    queryKey: ['marketing-pending-campaigns'],
    queryFn: async () => {
      const { data, error } = await supabase
        .from('marketing_campaigns')
        .select('*')
        .eq('status', 'pending')
        .order('created_at', { ascending: false });

      if (error) throw error;

      return (data || []).map((campaign): PendingCampaign => ({
        id: campaign.id,
        name: campaign.name,
        type: campaign.type as 'promotion' | 'flash_sale' | 'coupon' | 'membership',
        description: campaign.description || '',
        budget: (campaign.config as any)?.budget || 0,
        targetUsers: (campaign.config as any)?.target_users || 0,
        expectedROI: (campaign.config as any)?.expected_roi || 0,
        riskLevel: (campaign.config as any)?.risk_level || 'medium',
        createdAt: new Date(campaign.created_at),
        aiStrategy: campaign.ai_strategy || undefined
      }));
    }
  });

  // 获取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('marketing-insights', {
        headers: {
          Authorization: `Bearer ${session.access_token}`,
        },
      });

      if (error) throw error;
      
      if (data?.success && data?.insights?.length > 0) {
        // 转换时间戳为Date对象
        const formattedInsights: UnifiedInsight[] = data.insights.map((insight: any) => ({
          ...insight,
          timestamp: new Date(insight.timestamp)
        }));
        setInsights(formattedInsights);
        setLastUpdated(new Date());
        toast.success(`AI生成了 ${formattedInsights.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(() => ({
    insightCount: insights.filter(i => i.type !== 'auto_executed').length,
    pendingCount: pendingCampaigns.length,
    executedCount: insights.filter(i => i.type === 'auto_executed').length
  }), [insights, pendingCampaigns]);

  const handleInsightAction = (insightId: string, action: string) => {
    if (action === 'dismiss') {
      setInsights(prev => prev.filter(i => i.id !== insightId));
      toast.success("已标记为稍后处理");
    }
  };

  const handleCreateCampaign = (insight: UnifiedInsight) => {
    toast.info(`正在根据洞察创建活动: ${insight.title}`);
    onNavigateToCoupons?.();
  };

  // 根据洞察内容确定跳转目标
  const getInsightTargetTab = (insight: UnifiedInsight): string | null => {
    const { title, description } = insight;
    const content = `${title} ${description}`.toLowerCase();
    
    if (content.includes('订单') || 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 'products';
    }
    
    return 'marketing'; // 营销相关默认留在营销部
  };

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

  const handleApprove = async (id: string) => {
    try {
      const { error } = await supabase
        .from('marketing_campaigns')
        .update({ status: 'active', reviewed_at: new Date().toISOString() })
        .eq('id', id);

      if (error) throw error;

      queryClient.invalidateQueries({ queryKey: ['marketing-pending-campaigns'] });
      toast.success('已批准活动');
    } catch (error) {
      console.error('Error approving campaign:', error);
      toast.error('操作失败');
    }
  };

  const handleReject = async (id: string) => {
    try {
      const { error } = await supabase
        .from('marketing_campaigns')
        .update({ status: 'rejected', reviewed_at: new Date().toISOString() })
        .eq('id', id);

      if (error) throw error;

      queryClient.invalidateQueries({ queryKey: ['marketing-pending-campaigns'] });
      toast.info('已拒绝活动');
    } catch (error) {
      console.error('Error rejecting campaign:', error);
      toast.error('操作失败');
    }
  };

  const handleEdit = (id: string) => {
    toast.info("打开活动编辑面板...");
    // TODO: 打开编辑对话框
  };

  return (
    <div className="space-y-6">
      {/* Agent Settings Dialog */}
      <AgentSettingsDialog 
        open={settingsOpen} 
        onOpenChange={setSettingsOpen}
        agentType="marketing"
      />

      {/* 已处理任务弹窗 */}
      <CompletedTasksDialog 
        open={executedDialogOpen} 
        onOpenChange={setExecutedDialogOpen}
      />

      {/* 经理目标卡片 - 使用真实数据 */}
      <ManagerGoalCard goal={primaryGoal} loading={goalLoading} />
      
      {/* Agent状态栏 + 刷新按钮 */}
      <div className="flex items-center gap-4">
        <div className="flex-1">
          <AgentStatusBar
            status="running"
            insightCount={stats.insightCount}
            pendingCount={stats.pendingCount}
            executedCount={stats.executedCount}
            onSettingsClick={() => onOpenSettings ? onOpenSettings('marketing') : setSettingsOpen(true)}
            onExecutedClick={() => setExecutedDialogOpen(true)}
          />
        </div>
        <Button
          variant="outline"
          size="sm"
          onClick={fetchInsights}
          disabled={loading}
          className="shrink-0"
        >
          <RefreshCw className={`h-4 w-4 mr-2 ${loading ? 'animate-spin' : ''}`} />
          {loading ? '分析中...' : '刷新洞察'}
        </Button>
      </div>
      
      {/* 主内容区：洞察流 + 待审批 */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <UnifiedInsightFeed
          title="营销洞察"
          insights={insights}
          loading={loading}
          height="280px"
          onAction={handleInsightAction}
          onCreateCampaign={handleCreateCampaign}
          onClick={handleInsightClick}
          onRefresh={fetchInsights}
        />
        
        <PendingApprovals
          campaigns={pendingCampaigns}
          onApprove={handleApprove}
          onReject={handleReject}
          onEdit={handleEdit}
        />
      </div>
    </div>
  );
}
