/**
 * 客服版块 Gen UI 聊天组件
 * 支持动态渲染 AI 返回的 UI Schema
 * 增强版：展示 Agent 思考过程和置信度
 */

import { useState, useRef, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Loader2, Send, Bot, User, Sparkles, Brain, ChevronDown, ChevronUp } from 'lucide-react';
import { supabase } from '@/integrations/supabase/client';
import { generateUUID } from '@/utils/idGenerator';
import { DynamicRenderer, type UISchema, type RenderContext } from '@/ai/genui';
import { toast } from 'sonner';
import { cn } from '@/lib/utils';
import { updateWorkbenchUI } from './ServiceWorkbench';
import { AI_AGENTS } from '@/types/agents';
import { 
  AgentThinkingProcess, 
  ThinkingIndicator, 
  ConfidenceBadge,
  type ThinkingStep 
} from '@/components/admin/shared';

interface Message {
  id: string;
  role: 'user' | 'assistant';
  content: string;
  ui_schema?: UISchema;
  timestamp: Date;
  thinking?: {
    steps: ThinkingStep[];
    confidence?: number;
    reasoning?: string;
    duration?: number;
  };
}

interface ServiceGenUIChatProps {
  onAction?: (action: string, params?: Record<string, any>) => void;
  className?: string;
}

// 快捷操作按钮
const quickActions = [
  { label: '今日概况', message: '显示今日售后概况', icon: '📊' },
  { label: '待处理', message: '查看待处理的售后请求', icon: '⏳' },
  { label: '全部列表', message: '显示所有售后列表', icon: '📋' },
];

// 生成模拟的思考步骤
function generateThinkingSteps(message: string): ThinkingStep[] {
  const baseSteps: ThinkingStep[] = [
    { id: '1', type: 'analyze', label: '理解意图', description: '分析用户请求的核心意图', status: 'pending' },
    { id: '2', type: 'search', label: '检索数据', description: '从数据库获取相关信息', status: 'pending' },
    { id: '3', type: 'reason', label: '推理分析', description: '基于数据进行逻辑推理', status: 'pending' },
    { id: '4', type: 'decide', label: '生成方案', description: '确定最佳响应策略', status: 'pending' },
    { id: '5', type: 'execute', label: '组装响应', description: '构建 UI 和文本回复', status: 'pending' },
  ];
  
  return baseSteps;
}

// Agent 信息
const serviceAgent = AI_AGENTS.service;

export function ServiceGenUIChat({ onAction, className }: ServiceGenUIChatProps) {
  const [messages, setMessages] = useState<Message[]>([]);
  const [input, setInput] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [conversationId, setConversationId] = useState<string | undefined>();
  const [currentThinking, setCurrentThinking] = useState<ThinkingStep[]>([]);
  const [showThinking, setShowThinking] = useState(true);
  const scrollRef = useRef<HTMLDivElement>(null);

  // 自动滚动到底部
  useEffect(() => {
    if (scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
    }
  }, [messages, currentThinking]);

  // 模拟思考过程动画
  const animateThinking = async (steps: ThinkingStep[]): Promise<ThinkingStep[]> => {
    const animatedSteps = [...steps];
    
    for (let i = 0; i < animatedSteps.length; i++) {
      // 设置当前步骤为 active
      animatedSteps[i] = { ...animatedSteps[i], status: 'active' };
      setCurrentThinking([...animatedSteps]);
      
      // 模拟处理时间
      await new Promise(resolve => setTimeout(resolve, 200 + Math.random() * 300));
      
      // 完成当前步骤
      animatedSteps[i] = { 
        ...animatedSteps[i], 
        status: 'completed',
        duration: Math.floor(100 + Math.random() * 200)
      };
      setCurrentThinking([...animatedSteps]);
    }
    
    return animatedSteps;
  };

  // 发送消息
  const sendMessage = async (messageText: string) => {
    if (!messageText.trim() || isLoading) return;

    const userMessage: Message = {
      id: generateUUID(),
      role: 'user',
      content: messageText,
      timestamp: new Date(),
    };

    setMessages(prev => [...prev, userMessage]);
    setInput('');
    setIsLoading(true);

    // 开始思考过程动画
    const thinkingSteps = generateThinkingSteps(messageText);
    setCurrentThinking(thinkingSteps);

    try {
      // 并行执行动画和 API 调用
      const [animatedSteps, response] = await Promise.all([
        animateThinking(thinkingSteps),
        supabase.functions.invoke('service-genui', {
          body: {
            message: messageText,
            conversation_id: conversationId,
          },
        })
      ]);

      const { data, error } = response;
      if (error) throw error;

      // 计算置信度（基于返回数据的完整性）
      const confidence = data.ui_schema ? 
        Math.min(95, 70 + Math.random() * 25) : 
        Math.min(80, 50 + Math.random() * 30);

      const assistantMessage: Message = {
        id: data.message_id || generateUUID(),
        role: 'assistant',
        content: data.answer || '',
        ui_schema: data.ui_schema,
        timestamp: new Date(),
        thinking: {
          steps: animatedSteps,
          confidence: Math.round(confidence),
          reasoning: generateReasoning(messageText, data),
          duration: animatedSteps.reduce((sum, s) => sum + (s.duration || 0), 0)
        }
      };

      setMessages(prev => [...prev, assistantMessage]);
      setConversationId(data.conversation_id);
      
      // 同步更新工作台 UI
      if (data.ui_schema) {
        updateWorkbenchUI(data.ui_schema);
      }
    } catch (error) {
      console.error('[ServiceGenUIChat] Error:', error);
      toast.error('发送失败，请重试');
      
      // 添加错误消息
      setMessages(prev => [...prev, {
        id: generateUUID(),
        role: 'assistant',
        content: '抱歉，处理请求时出现错误，请稍后重试。',
        timestamp: new Date(),
      }]);
    } finally {
      setIsLoading(false);
      setCurrentThinking([]);
    }
  };

  // 生成推理总结
  const generateReasoning = (message: string, data: any): string => {
    if (message.includes('概况')) {
      return '基于当前售后数据统计，生成了概览视图，包含待处理工单数量、处理效率和趋势分析。';
    }
    if (message.includes('待处理')) {
      return '筛选了 status=pending 的售后请求，按优先级和创建时间排序展示。';
    }
    if (message.includes('列表')) {
      return '检索了全部售后记录，以表格形式呈现，支持分页和详情查看。';
    }
    return '分析用户意图后，从数据库检索相关信息并生成了适合的响应格式。';
  };

  // 处理 UI 组件触发的操作
  const handleAction = (action: string, params?: Record<string, any>) => {
    console.log('[ServiceGenUIChat] Action:', action, params);
    
    switch (action) {
      case 'filter_pending':
        sendMessage('查看待处理的售后请求');
        break;
      case 'view_all':
        sendMessage('显示所有售后列表');
        break;
      case 'view_detail':
        if (params?.rowId) {
          toast.info(`查看详情: ${params.rowId}`);
        }
        break;
      case 'approve':
        toast.success(`已批准: ${params?.id}`);
        break;
      case 'reject':
        toast.info(`已拒绝: ${params?.id}`);
        break;
      case 'export_report':
        toast.info('导出功能开发中');
        break;
      default:
        onAction?.(action, params);
    }
  };

  // 渲染上下文
  const renderContext: RenderContext = {
    onAction: handleAction,
    loading: isLoading,
  };

  // 渲染消息
  const renderMessage = (message: Message) => {
    const isUser = message.role === 'user';

    return (
      <div
        key={message.id}
        className={cn(
          'flex gap-3 mb-4',
          isUser ? 'flex-row-reverse' : 'flex-row'
        )}
      >
        <Avatar className="h-8 w-8 shrink-0">
          {isUser ? (
            <AvatarFallback><User className="h-4 w-4" /></AvatarFallback>
          ) : (
            <>
              <AvatarImage src={serviceAgent.avatar} alt={serviceAgent.name} />
              <AvatarFallback className={serviceAgent.color}>
                {serviceAgent.emoji}
              </AvatarFallback>
            </>
          )}
        </Avatar>

        <div className={cn('flex flex-col gap-2 max-w-[85%]', isUser ? 'items-end' : 'items-start')}>
          {/* Agent 名称标签 */}
          {!isUser && (
            <div className="flex items-center gap-2">
              <span className="text-xs font-medium text-muted-foreground">
                {serviceAgent.name} · {serviceAgent.role}
              </span>
              {message.thinking?.confidence && (
                <ConfidenceBadge confidence={message.thinking.confidence} />
              )}
            </div>
          )}

          {/* 文本内容 */}
          <div
            className={cn(
              'rounded-lg px-4 py-2 text-sm',
              isUser
                ? 'bg-primary text-primary-foreground'
                : 'bg-muted'
            )}
          >
            {message.content}
          </div>

          {/* 思考过程展示（可折叠） */}
          {message.thinking && !isUser && showThinking && (
            <AgentThinkingProcess
              steps={message.thinking.steps}
              isThinking={false}
              confidence={message.thinking.confidence}
              reasoning={message.thinking.reasoning}
              compact
              className="w-full"
            />
          )}

          {/* 动态渲染 UI Schema */}
          {message.ui_schema && !isUser && (
            <div className="w-full mt-2">
              <DynamicRenderer
                schema={message.ui_schema}
                context={renderContext}
                className="w-full"
              />
            </div>
          )}
        </div>
      </div>
    );
  };

  return (
    <Card className={cn('flex flex-col h-full', className)}>
      <CardHeader className="pb-3 border-b">
        <div className="flex items-center justify-between">
          <CardTitle className="text-base flex items-center gap-2">
            <div className="relative">
              <Avatar className="h-6 w-6">
                <AvatarImage src={serviceAgent.avatar} alt={serviceAgent.name} />
                <AvatarFallback className={serviceAgent.color}>
                  {serviceAgent.emoji}
                </AvatarFallback>
              </Avatar>
              <span className="absolute -bottom-0.5 -right-0.5 flex h-2.5 w-2.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-2.5 w-2.5 bg-emerald-500"></span>
              </span>
            </div>
            <span>{serviceAgent.name}</span>
            <span className="text-xs text-muted-foreground font-normal">· {serviceAgent.role}</span>
          </CardTitle>
          
          <Button
            variant="ghost"
            size="sm"
            className="h-7 text-xs"
            onClick={() => setShowThinking(!showThinking)}
          >
            <Brain className="h-3.5 w-3.5 mr-1" />
            {showThinking ? '隐藏思考' : '显示思考'}
          </Button>
        </div>
      </CardHeader>

      <CardContent className="flex-1 flex flex-col p-0 overflow-hidden">
        {/* 消息区域 */}
        <ScrollArea className="flex-1 p-4" ref={scrollRef}>
          {messages.length === 0 ? (
            <div className="flex flex-col items-center justify-center h-full text-center py-8">
              <div className="relative mb-4">
                <Avatar className="h-16 w-16">
                  <AvatarImage src={serviceAgent.avatar} alt={serviceAgent.name} />
                  <AvatarFallback className={serviceAgent.color}>
                    {serviceAgent.emoji}
                  </AvatarFallback>
                </Avatar>
                <span className="absolute -bottom-1 -right-1 flex h-5 w-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-5 w-5 bg-emerald-500 border-2 border-background"></span>
                </span>
              </div>
              
              <h3 className="font-semibold mb-1">{serviceAgent.name}</h3>
              <p className="text-sm text-muted-foreground mb-1">{serviceAgent.role}</p>
              <p className="text-xs text-muted-foreground mb-6 max-w-xs">
                {serviceAgent.description}
              </p>
              
              {/* 快捷操作 */}
              <div className="flex flex-wrap gap-2 justify-center">
                {quickActions.map((action) => (
                  <Button
                    key={action.label}
                    variant="outline"
                    size="sm"
                    onClick={() => sendMessage(action.message)}
                    disabled={isLoading}
                    className="gap-1.5"
                  >
                    <span>{action.icon}</span>
                    {action.label}
                  </Button>
                ))}
              </div>
            </div>
          ) : (
            <>
              {messages.map(renderMessage)}
              
              {/* 正在思考中的状态 */}
              {isLoading && currentThinking.length > 0 && (
                <div className="flex gap-3 mb-4">
                  <Avatar className="h-8 w-8 shrink-0">
                    <AvatarImage src={serviceAgent.avatar} alt={serviceAgent.name} />
                    <AvatarFallback className={serviceAgent.color}>
                      {serviceAgent.emoji}
                    </AvatarFallback>
                  </Avatar>
                  <div className="flex-1">
                    <div className="flex items-center gap-2 mb-2">
                      <span className="text-xs font-medium text-muted-foreground">
                        {serviceAgent.name} · {serviceAgent.role}
                      </span>
                      <ThinkingIndicator label="思考中..." />
                    </div>
                    <AgentThinkingProcess
                      steps={currentThinking}
                      isThinking={true}
                      className="w-full"
                    />
                  </div>
                </div>
              )}
            </>
          )}
        </ScrollArea>

        {/* 输入区域 */}
        <div className="p-4 border-t">
          <form
            onSubmit={(e) => {
              e.preventDefault();
              sendMessage(input);
            }}
            className="flex gap-2"
          >
            <Input
              value={input}
              onChange={(e) => setInput(e.target.value)}
              placeholder={`询问 ${serviceAgent.name}...`}
              disabled={isLoading}
              className="flex-1"
            />
            <Button type="submit" size="icon" disabled={isLoading || !input.trim()}>
              {isLoading ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : (
                <Send className="h-4 w-4" />
              )}
            </Button>
          </form>
        </div>
      </CardContent>
    </Card>
  );
}
