/**
 * 商品版块 Gen UI 聊天组件
 * 支持动态渲染 AI 返回的 UI Schema
 */

import { useState, useRef, useEffect, useCallback } 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 } from '@/components/ui/avatar';
import { Loader2, Send, Bot, User, Sparkles } 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 { 
  subscribeToProductAIMessage, 
  updateProductWorkbenchUI 
} from './ProductWorkbench';

interface Message {
  id: string;
  role: 'user' | 'assistant';
  content: string;
  ui_schema?: UISchema;
  timestamp: Date;
}

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

// 快捷操作按钮
const quickActions = [
  { label: '商品概览', message: '显示商品工作台概览' },
  { label: '低库存', message: '查看低库存商品' },
  { label: '滞销商品', message: '查看滞销商品' },
];

export function ProductGenUIChat({ onAction, className }: ProductGenUIChatProps) {
  const [messages, setMessages] = useState<Message[]>([]);
  const [input, setInput] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [conversationId, setConversationId] = useState<string | undefined>();
  const scrollRef = useRef<HTMLDivElement>(null);
  
  // 使用 ref 存储最新的 conversationId，避免闭包问题
  const conversationIdRef = useRef<string | undefined>();
  useEffect(() => {
    conversationIdRef.current = conversationId;
  }, [conversationId]);

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

  // 发送消息 - 使用 useCallback 并处理闭包问题
  const sendMessage = useCallback(async (messageText: string) => {
    if (!messageText.trim()) return;

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

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

    try {
      const { data: { session } } = await supabase.auth.getSession();
      
      const { data, error } = await supabase.functions.invoke('product-genui', {
        body: {
          message: messageText,
          conversation_id: conversationIdRef.current,
        },
        headers: session?.access_token ? {
          Authorization: `Bearer ${session.access_token}`
        } : undefined
      });

      if (error) throw error;

      console.log('[ProductGenUIChat] Response received:', { 
        hasSchema: !!data.ui_schema,
        answer: data.answer?.substring(0, 50) 
      });

      const assistantMessage: Message = {
        id: data.message_id || generateUUID(),
        role: 'assistant',
        content: data.answer || '',
        ui_schema: data.ui_schema,
        timestamp: new Date(),
      };

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

      // 同步 UI Schema 到工作台
      if (data.ui_schema) {
        console.log('[ProductGenUIChat] Updating workbench UI');
        updateProductWorkbenchUI(data.ui_schema);
      }
    } catch (error) {
      console.error('[ProductGenUIChat] Error:', error);
      toast.error('发送失败，请重试');
      
      setMessages(prev => [...prev, {
        id: generateUUID(),
        role: 'assistant',
        content: '抱歉，处理请求时出现错误，请稍后重试。',
        timestamp: new Date(),
      }]);
    } finally {
      setIsLoading(false);
    }
  }, []);

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

  // 处理 UI 组件触发的操作
  const handleAction = (action: string, params?: Record<string, any>) => {
    console.log('[ProductGenUIChat] Action:', action, params);
    
    // 导航操作
    if (action.startsWith('navigate:')) {
      const target = action.replace('navigate:', '');
      const intentMap: Record<string, string> = {
        dashboard: '显示商品工作台概览',
        products_list: '查看全部商品',
        products_low_stock: '查看低库存商品',
        products_slow_moving: '查看滞销商品',
      };
      if (intentMap[target]) {
        sendMessage(intentMap[target]);
      }
      return;
    }

    switch (action) {
      case 'view_detail':
        if (params?.rowId) {
          toast.info(`查看详情: ${params.rowId}`);
        }
        break;
      case 'export_analytics':
        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>
          ) : (
            <AvatarFallback className="bg-primary text-primary-foreground">
              <Bot className="h-4 w-4" />
            </AvatarFallback>
          )}
        </Avatar>

        <div className={cn('flex flex-col gap-2 max-w-[85%]', isUser ? 'items-end' : 'items-start')}>
          {/* 文本内容 */}
          <div
            className={cn(
              'rounded-lg px-4 py-2 text-sm',
              isUser
                ? 'bg-primary text-primary-foreground'
                : 'bg-muted'
            )}
          >
            {message.content}
          </div>

          {/* 动态渲染 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">
        <CardTitle className="text-base flex items-center gap-2">
          <Sparkles className="h-4 w-4 text-primary" />
          Gen UI 商品助手
        </CardTitle>
      </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">
              <Bot className="h-12 w-12 text-muted-foreground mb-4" />
              <h3 className="font-medium mb-2">Gen UI 商品助手</h3>
              <p className="text-sm text-muted-foreground mb-6">
                我可以帮您查看商品概况、库存分析等
              </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}
                  >
                    {action.label}
                  </Button>
                ))}
              </div>
            </div>
          ) : (
            <>
              {messages.map(renderMessage)}
              {isLoading && (
                <div className="flex gap-3 mb-4">
                  <Avatar className="h-8 w-8">
                    <AvatarFallback className="bg-primary text-primary-foreground">
                      <Bot className="h-4 w-4" />
                    </AvatarFallback>
                  </Avatar>
                  <div className="bg-muted rounded-lg px-4 py-2">
                    <Loader2 className="h-4 w-4 animate-spin" />
                  </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="输入问题，如：低库存商品..."
              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>
  );
}
