import { useState, 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 { 
  CheckCircle2, 
  Clock, 
  ThumbsUp,
  ThumbsDown,
  Target
} from "lucide-react";
import { Progress } from "@/components/ui/progress";
import { ManagerGoal } from "../marketing/ManagerGoalCard";
import { AgentSettingsDialog } from "../team";
import { supabase } from "@/integrations/supabase/client";
import { toast } from "sonner";
import { 
  UnifiedInsightFeed, 
  UnifiedInsight, 
  CompletedTasksDialog,
} from "../shared";
import { AgentDashboard } from "./AgentDashboard";
import { useQuery, useQueryClient } from "@tanstack/react-query";

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

interface PendingApproval {
  id: string;
  type: string;
  title: string;
  description: string;
  items: number;
  createdBy: string;
  priority: 'urgent' | 'normal';
  requestType?: string;
  refundAmount?: number;
}

// 模拟经理目标
const mockGoal: ManagerGoal = {
  id: "1",
  title: "提升客户满意度至95%",
  description: "本月目标：客户满意度达到95%，售后处理时效控制在24小时内",
  targetValue: 95,
  currentValue: 91,
  unit: "%",
  deadline: new Date("2024-12-31"),
  assignedBy: "店铺经理(小管)",
  priority: "high"
};



// ============ 子组件 ============

// 目标进度卡片（紧凑版）
function GoalProgressCard({ goal }: { goal: ManagerGoal }) {
  const progress = Math.min((goal.currentValue / goal.targetValue) * 100, 100);
  const daysLeft = Math.ceil((goal.deadline.getTime() - Date.now()) / (1000 * 60 * 60 * 24));
  
  return (
    <Card className="border-primary/20 bg-gradient-to-br from-primary/5 to-transparent">
      <CardContent className="p-4">
        <div className="flex items-center gap-3 mb-3">
          <div className="p-2 rounded-lg bg-primary/20">
            <Target className="h-4 w-4 text-primary" />
          </div>
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2">
              <h4 className="font-medium text-sm truncate">{goal.title}</h4>
              <Badge variant="secondary" className="text-xs bg-amber-500/20 text-amber-600 shrink-0">
                重要
              </Badge>
            </div>
            <p className="text-xs text-muted-foreground">来自 {goal.assignedBy}</p>
          </div>
          <div className="text-right shrink-0">
            <p className="text-lg font-bold">{goal.currentValue}{goal.unit}</p>
            <p className="text-xs text-muted-foreground">目标 {goal.targetValue}{goal.unit}</p>
          </div>
        </div>
        <div className="space-y-1.5">
          <Progress value={progress} className="h-2" />
          <div className="flex items-center justify-between text-xs text-muted-foreground">
            <span>{progress.toFixed(0)}% 完成</span>
            <span className="flex items-center gap-1">
              <Clock className="h-3 w-3" />
              剩余 {daysLeft} 天
            </span>
          </div>
        </div>
      </CardContent>
    </Card>
  );
}

// 待审批列表（紧凑版）
function PendingApprovalsList({ 
  approvals, 
  onApprove, 
  onReject 
}: { 
  approvals: PendingApproval[];
  onApprove: (type: string) => void;
  onReject: (type: string) => void;
}) {
  return (
    <Card className="h-full flex flex-col">
      <CardHeader className="pb-2 shrink-0">
        <div className="flex items-center justify-between">
          <CardTitle className="text-sm flex items-center gap-2">
            <Clock className="h-4 w-4 text-primary" />
            待审批
          </CardTitle>
          <Badge variant="destructive" className="text-xs">
            {approvals.reduce((sum, a) => sum + a.items, 0)} 项
          </Badge>
        </div>
      </CardHeader>
      <CardContent className="flex-1 p-0 overflow-hidden">
        <ScrollArea className="h-full">
          <div className="space-y-2 p-4 pt-0">
            {approvals.length === 0 ? (
              <div className="flex flex-col items-center justify-center py-8 text-muted-foreground">
                <CheckCircle2 className="h-8 w-8 mb-2 opacity-20" />
                <p className="text-sm">暂无待审批</p>
              </div>
            ) : (
              approvals.map((approval) => (
                <div
                  key={approval.id}
                  className="p-3 rounded-lg border bg-card hover:bg-accent/30 transition-colors"
                >
                  <div className="flex items-center justify-between gap-2 mb-2">
                    <div className="flex items-center gap-2">
                      <h4 className="font-medium text-sm">{approval.title}</h4>
                      {approval.priority === "urgent" && (
                        <Badge variant="destructive" className="text-xs">紧急</Badge>
                      )}
                    </div>
                    <Badge variant="outline" className="text-xs">
                      {approval.items} 项
                    </Badge>
                  </div>
                  
                  {approval.refundAmount && approval.refundAmount > 0 && (
                    <p className="text-xs text-amber-600 mb-2">
                      涉及金额: ¥{approval.refundAmount.toFixed(2)}
                    </p>
                  )}
                  
                  <div className="flex items-center gap-2">
                    <Button 
                      size="sm" 
                      className="h-7 text-xs flex-1"
                      onClick={() => onApprove(approval.requestType || '')}
                    >
                      <ThumbsUp className="h-3 w-3 mr-1" />
                      批准
                    </Button>
                    <Button 
                      size="sm" 
                      variant="outline" 
                      className="h-7 text-xs flex-1"
                      onClick={() => onReject(approval.requestType || '')}
                    >
                      <ThumbsDown className="h-3 w-3 mr-1" />
                      拒绝
                    </Button>
                  </div>
                </div>
              ))
            )}
          </div>
        </ScrollArea>
      </CardContent>
    </Card>
  );
}

// ============ 主组件 ============

export function AfterSalesAICockpit({ onNavigate }: AfterSalesAICockpitProps) {
  const [agentSettingsOpen, setAgentSettingsOpen] = useState(false);
  const [executedDialogOpen, setExecutedDialogOpen] = useState(false);
  const [insights, setInsights] = useState<UnifiedInsight[]>([]);
  const [loading, setLoading] = useState(false);
  const queryClient = useQueryClient();

  // 从数据库获取待审批售后请求
  const { data: pendingApprovals = [] } = useQuery({
    queryKey: ['service-pending-approvals'],
    queryFn: async () => {
      const { data, error } = await supabase
        .from('after_sales_requests')
        .select(`
          id,
          type,
          reason,
          description,
          refund_amount,
          status,
          created_at,
          products:product_id (name)
        `)
        .eq('status', 'pending')
        .order('created_at', { ascending: false });

      if (error) throw error;

      // 按类型分组
      const typeGroups: Record<string, any[]> = {};
      (data || []).forEach(item => {
        const key = item.type;
        if (!typeGroups[key]) typeGroups[key] = [];
        typeGroups[key].push(item);
      });

      // 转换为审批项
      const approvals: PendingApproval[] = Object.entries(typeGroups).map(([type, items]) => ({
        id: items[0].id,
        type: type === 'refund' ? 'refund_batch' : type === 'return' ? 'return_batch' : 'other',
        title: type === 'refund' ? '退款申请' : type === 'return' ? '退货申请' : '换货申请',
        description: `${items.length}个${type === 'refund' ? '退款' : type === 'return' ? '退货' : '换货'}请求待处理`,
        items: items.length,
        createdBy: 'AI',
        priority: items.some(i => Date.now() - new Date(i.created_at).getTime() > 24 * 60 * 60 * 1000) ? 'urgent' as const : 'normal' as const,
        requestType: type,
        refundAmount: items.reduce((sum, i) => sum + (i.refund_amount || 0), 0)
      }));

      return approvals;
    }
  });

  const handleApproveAll = async (type: string) => {
    try {
      const { error } = await supabase
        .from('after_sales_requests')
        .update({ status: 'approved', processed_at: new Date().toISOString() })
        .eq('status', 'pending')
        .eq('type', type);

      if (error) throw error;

      queryClient.invalidateQueries({ queryKey: ['service-pending-approvals'] });
      toast.success('已批量批准');
    } catch (error) {
      console.error('Error approving requests:', error);
      toast.error('操作失败');
    }
  };

  const handleRejectAll = async (type: string) => {
    try {
      const { error } = await supabase
        .from('after_sales_requests')
        .update({ status: 'rejected', processed_at: new Date().toISOString() })
        .eq('status', 'pending')
        .eq('type', type);

      if (error) throw error;

      queryClient.invalidateQueries({ queryKey: ['service-pending-approvals'] });
      toast.info('已批量拒绝');
    } catch (error) {
      console.error('Error rejecting requests:', error);
      toast.error('操作失败');
    }
  };

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

      if (error) throw error;
      
      if (data?.success && data?.insights?.length > 0) {
        const formattedInsights = data.insights.map((insight: any) => ({
          ...insight,
          timestamp: new Date(insight.timestamp)
        }));
        setInsights(formattedInsights);
        toast.success(`AI生成了 ${formattedInsights.length} 条服务洞察`);
      } else if (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 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 'marketing';
    }
    if (content.includes('商品') || content.includes('库存') || content.includes('上架')) {
      return 'products';
    }
    
    return 'aftersales';
  };

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

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

  // 获取已处理售后请求数量
  const { data: executedCount = 0 } = useQuery({
    queryKey: ['service-executed-count'],
    queryFn: async () => {
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      
      const { count, error } = await supabase
        .from('after_sales_requests')
        .select('*', { count: 'exact', head: true })
        .in('status', ['approved', 'rejected', 'completed'])
        .gte('processed_at', today.toISOString());

      if (error) throw error;
      return count || 0;
    }
  });

  return (
    <div className="space-y-4 h-full flex flex-col">
      {/* 已处理任务弹窗 */}
      <CompletedTasksDialog 
        open={executedDialogOpen} 
        onOpenChange={setExecutedDialogOpen}
      />

      {/* 顶部状态栏：Agent状态 + 目标进度 */}
      <div className="grid grid-cols-12 gap-4">
        <div className="col-span-5">
          <AgentDashboard onSettingsClick={() => setAgentSettingsOpen(true)} />
        </div>
        <div className="col-span-7">
          <GoalProgressCard goal={mockGoal} />
        </div>
      </div>

      {/* 主工作区 - 双栏布局 */}
      <div className="flex-1 grid grid-cols-12 gap-4 min-h-0">
        {/* 左栏：AI洞察 */}
        <div className="col-span-7 min-h-0">
          <UnifiedInsightFeed
            title="AI洞察"
            insights={insights}
            loading={loading}
            height="100%"
            onAction={handleInsightAction}
            onClick={handleInsightClick}
            onRefresh={fetchInsights}
            emptyText="暂无洞察"
            emptySubText="点击刷新获取AI分析"
          />
        </div>

        {/* 右栏：待审批 */}
        <div className="col-span-5 min-h-0">
          <PendingApprovalsList
            approvals={pendingApprovals}
            onApprove={handleApproveAll}
            onReject={handleRejectAll}
          />
        </div>
      </div>

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