/**
 * 店长版块 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, Brain } 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 { 
  subscribeToManagerAIMessage, 
  updateManagerWorkbenchUI 
} from './ManagerWorkbench';
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 ManagerGenUIChatProps {
  onAction?: (action: string, params?: Record<string, any>) => void;
  className?: string;
}

// 快捷操作按钮
const quickActions = [
  { label: '经营概览', message: '显示店长工作台概览', icon: '📊' },
  { label: '订单统计', message: '查看订单统计', icon: '📦' },
  { label: '库存状况', message: '查看商品库存情况', icon: '📋' },
];

// 生成模拟的思考步骤
function generateThinkingSteps(): ThinkingStep[] {
  return [
    { 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' },
  ];
}

// Agent 信息
const managerAgent = AI_AGENTS.manager;

export function ManagerGenUIChat({ onAction, className }: ManagerGenUIChatProps) {
  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]);

  // 监听工作台发来的消息
  useEffect(() => {
    const unsubscribe = subscribeToManagerAIMessage((message) => {
      console.log('[ManagerGenUIChat] Received message from workbench:', message);
      sendMessage(message);
    });
    return () => { unsubscribe(); };
  }, []);

  // 模拟思考过程动画
  const animateThinking = async (steps: ThinkingStep[]): Promise<ThinkingStep[]> => {
    const animatedSteps = [...steps];
    
    for (let i = 0; i < animatedSteps.length; i++) {
      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();
    setCurrentThinking(thinkingSteps);

    try {
      const { data: { session } } = await supabase.auth.getSession();
      
      const [animatedSteps, response] = await Promise.all([
        animateThinking(thinkingSteps),
        supabase.functions.invoke('manager-genui', {
          body: {
            message: messageText,
            conversation_id: conversationId,
          },
          headers: session?.access_token ? {
            Authorization: `Bearer ${session.access_token}`
          } : undefined
        })
      ]);

      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),
          duration: animatedSteps.reduce((sum, s) => sum + (s.duration || 0), 0)
        }
      };

      setMessages(prev => [...prev, assistantMessage]);
      setConversationId(data.conversation_id);

      if (data.ui_schema) {
        updateManagerWorkbenchUI(data.ui_schema);
      }
    } catch (error) {
      console.error('[ManagerGenUIChat] Error:', error);
      toast.error('发送失败，请重试');
      
      setMessages(prev => [...prev, {
        id: generateUUID(),
        role: 'assistant',
        content: '抱歉，处理请求时出现错误，请稍后重试。',
        timestamp: new Date(),
      }]);
    } finally {
      setIsLoading(false);
      setCurrentThinking([]);
    }
  };

  // 生成推理总结
  const generateReasoning = (message: string): string => {
    if (message.includes('概览')) {
      return '基于全店经营数据统计，生成了概览视图，包含各部门KPI、订单趋势和库存状况。';
    }
    if (message.includes('订单')) {
      return '检索了订单数据，按状态和时间维度进行统计分析。';
    }
    if (message.includes('库存')) {
      return '检索了商品库存记录，识别低库存和滞销商品。';
    }
    return '分析用户意图后，从数据库检索相关信息并生成了适合的响应格式。';
  };

  // 处理 UI 组件触发的操作
  const handleAction = (action: string, params?: Record<string, any>) => {
    console.log('[ManagerGenUIChat] Action:', action, params);
    
    switch (action) {
      case 'view_orders':
        sendMessage('查看订单统计');
        break;
      case 'view_products':
        sendMessage('查看商品库存情况');
        break;
      case 'view_marketing':
        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;
      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={managerAgent.avatar} alt={managerAgent.name} />
              <AvatarFallback className={managerAgent.color}>
                {managerAgent.emoji}
              </AvatarFallback>
            </>
          )}
        </Avatar>

        <div className={cn('flex flex-col gap-2 max-w-[85%]', isUser ? 'items-end' : 'items-start')}>
          {!isUser && (
            <div className="flex items-center gap-2">
              <span className="text-xs font-medium text-muted-foreground">
                {managerAgent.name} · {managerAgent.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"
            />
          )}

          {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={managerAgent.avatar} alt={managerAgent.name} />
                <AvatarFallback className={managerAgent.color}>
                  {managerAgent.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>{managerAgent.name}</span>
            <span className="text-xs text-muted-foreground font-normal">· {managerAgent.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={managerAgent.avatar} alt={managerAgent.name} />
                  <AvatarFallback className={managerAgent.color}>
                    {managerAgent.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">{managerAgent.name}</h3>
              <p className="text-sm text-muted-foreground mb-1">{managerAgent.role}</p>
              <p className="text-xs text-muted-foreground mb-6 max-w-xs">
                {managerAgent.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={managerAgent.avatar} alt={managerAgent.name} />
                    <AvatarFallback className={managerAgent.color}>
                      {managerAgent.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">
                        {managerAgent.name} · {managerAgent.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={`询问 ${managerAgent.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>
  );
}
