/**
 * 客服 Gen UI 控制台
 * 完全由 AI 驱动的动态界面 - 所有视图通过 UI Schema 生成
 */

import { useState, useEffect, useCallback, useRef } from "react";
import { generateUUID } from '@/utils/idGenerator';
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Separator } from "@/components/ui/separator";
import { 
  Bot, 
  Send, 
  Sparkles, 
  RefreshCw,
  Loader2,
  MessageSquare,
  Mic,
  MicOff
} from "lucide-react";
import { DynamicRenderer } from "@/ai/genui/DynamicRenderer";
import type { UISchema, RenderContext } from "@/ai/genui/types";
import { supabase } from "@/integrations/supabase/client";
import { toast } from "sonner";
import { cn } from "@/lib/utils";

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

interface ServiceGenUIDashboardProps {
  className?: string;
}

export function ServiceGenUIDashboard({ className }: ServiceGenUIDashboardProps) {
  const [messages, setMessages] = useState<Message[]>([]);
  const [input, setInput] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [conversationId, setConversationId] = useState<string>();
  const [currentView, setCurrentView] = useState<string>('dashboard');
  const scrollRef = useRef<HTMLDivElement>(null);

  // 初始化 - 自动发送欢迎消息
  useEffect(() => {
    sendMessage('你好，显示概况');
  }, []);

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

  const sendMessage = useCallback(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);

    try {
      const { data: { session } } = await supabase.auth.getSession();
      if (!session) {
        toast.error("请先登录");
        setIsLoading(false);
        return;
      }

      const { data, error } = await supabase.functions.invoke('service-genui', {
        body: { 
          message: messageText,
          conversation_id: conversationId,
          context: {
            current_view: currentView,
          },
        },
        headers: {
          Authorization: `Bearer ${session.access_token}`,
        },
      });

      if (error) throw error;

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

      setMessages(prev => [...prev, assistantMessage]);
      
      if (data.conversation_id) {
        setConversationId(data.conversation_id);
      }
    } catch (error) {
      console.error('[ServiceGenUI] Error:', error);
      toast.error("请求失败，请重试");
      
      const errorMessage: Message = {
        id: generateUUID(),
        role: 'assistant',
        content: '抱歉，处理请求时出现错误，请稍后重试。',
        timestamp: new Date(),
      };
      setMessages(prev => [...prev, errorMessage]);
    } finally {
      setIsLoading(false);
    }
  }, [conversationId, currentView, isLoading]);

  // 处理 Gen UI 组件的操作
  const handleAction = useCallback((action: string, params?: Record<string, any>) => {
    console.log('[ServiceGenUI] Action:', action, params);

    // 处理导航操作
    if (action.startsWith('navigate:')) {
      const target = action.replace('navigate:', '');
      setCurrentView(target);
      
      const navigationMap: Record<string, string> = {
        'dashboard': '显示概况',
        'after_sales_pending': '查看待处理售后',
        'after_sales_list': '查看售后列表',
        'orders_to_ship': '查看待发货订单',
        'orders_list': '查看订单列表',
        'customers_list': '查看客户列表',
      };

      const command = navigationMap[target];
      if (command) {
        sendMessage(command);
      }
      return;
    }

    // 处理其他操作
    switch (action) {
      case 'approve_request':
        toast.success(`已批准售后请求 ${params?.id}`);
        // TODO: 调用后端 API
        break;
      case 'reject_request':
        toast.info(`已拒绝售后请求 ${params?.id}`);
        break;
      case 'ship_order':
        toast.info(`准备发货订单 ${params?.id}`);
        break;
      case 'view_detail':
      case 'view_order':
      case 'view_customer':
        toast.info(`查看详情 ${params?.id}`);
        break;
      case 'export_aftersales':
      case 'export_orders':
      case 'export_customers':
        toast.info('导出功能开发中...');
        break;
      default:
        console.log('[ServiceGenUI] Unhandled action:', action);
    }
  }, [sendMessage]);

  // 渲染上下文
  const renderContext: RenderContext = {
    onAction: handleAction,
    theme: 'light',
  };

  // 快捷操作
  const quickActions = [
    { label: '概况', command: '显示概况' },
    { label: '待处理售后', command: '查看待处理售后' },
    { label: '待发货订单', command: '查看待发货订单' },
    { label: '客户列表', command: '查看客户列表' },
    { label: '帮助', command: '帮助' },
  ];

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    sendMessage(input);
  };

  const handleQuickAction = (command: string) => {
    sendMessage(command);
  };

  // 获取最新的助手消息的 UI Schema
  const latestAssistantMessage = [...messages].reverse().find(m => m.role === 'assistant');

  return (
    <div className={cn("flex flex-col h-full", className)}>
      {/* 头部 */}
      <div className="flex-shrink-0 border-b bg-background/95 backdrop-blur p-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="relative">
              <div className="h-10 w-10 rounded-full bg-primary/20 flex items-center justify-center">
                <Bot className="h-5 w-5 text-primary" />
              </div>
              <span className="absolute -bottom-0.5 -right-0.5 flex h-3 w-3">
                <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-3 w-3 bg-emerald-500"></span>
              </span>
            </div>
            <div>
              <h2 className="font-semibold flex items-center gap-2">
                客服智能助手
                <Badge variant="secondary" className="text-xs">
                  <Sparkles className="h-3 w-3 mr-1" />
                  Gen UI
                </Badge>
              </h2>
              <p className="text-xs text-muted-foreground">AI 驱动的动态界面</p>
            </div>
          </div>
          <Button
            variant="ghost"
            size="sm"
            onClick={() => {
              setMessages([]);
              sendMessage('你好，显示概况');
            }}
          >
            <RefreshCw className="h-4 w-4 mr-1" />
            重置
          </Button>
        </div>

        {/* 快捷操作 */}
        <div className="flex gap-2 mt-4 flex-wrap">
          {quickActions.map((action) => (
            <Button
              key={action.command}
              variant="outline"
              size="sm"
              className="text-xs"
              onClick={() => handleQuickAction(action.command)}
              disabled={isLoading}
            >
              {action.label}
            </Button>
          ))}
        </div>
      </div>

      {/* 主内容区 - 动态渲染 */}
      <ScrollArea className="flex-1 p-4" ref={scrollRef}>
        <div className="space-y-4">
          {/* 显示最新的 UI Schema */}
          {latestAssistantMessage?.ui_schema && (
            <Card className="border-primary/20">
              <CardContent className="p-4">
                {/* 助手回复文本 */}
                <div className="flex items-start gap-3 mb-4">
                  <div className="h-8 w-8 rounded-full bg-primary/20 flex items-center justify-center flex-shrink-0">
                    <Bot className="h-4 w-4 text-primary" />
                  </div>
                  <div className="flex-1">
                    <p className="text-sm text-muted-foreground">{latestAssistantMessage.content}</p>
                  </div>
                </div>
                
                <Separator className="my-4" />

                {/* 动态渲染 UI */}
                <DynamicRenderer 
                  schema={latestAssistantMessage.ui_schema} 
                  context={renderContext}
                  className="mt-2"
                />
              </CardContent>
            </Card>
          )}

          {/* 建议操作 */}
          {latestAssistantMessage?.suggested_actions && latestAssistantMessage.suggested_actions.length > 0 && (
            <div className="flex gap-2 flex-wrap">
              <span className="text-xs text-muted-foreground self-center">建议操作：</span>
              {latestAssistantMessage.suggested_actions.map((action, idx) => (
                <Button
                  key={idx}
                  variant="ghost"
                  size="sm"
                  className="text-xs h-7"
                  onClick={() => handleQuickAction(action)}
                  disabled={isLoading}
                >
                  {action}
                </Button>
              ))}
            </div>
          )}

          {/* 对话历史（折叠显示） */}
          {messages.length > 2 && (
            <details className="text-xs text-muted-foreground">
              <summary className="cursor-pointer hover:text-foreground">
                查看对话历史 ({messages.length} 条消息)
              </summary>
              <div className="mt-2 space-y-2 pl-4 border-l-2">
                {messages.slice(0, -1).map((msg) => (
                  <div key={msg.id} className={cn(
                    "p-2 rounded",
                    msg.role === 'user' ? 'bg-muted' : 'bg-background'
                  )}>
                    <span className="font-medium">{msg.role === 'user' ? '您' : '助手'}:</span>
                    <span className="ml-2">{msg.content}</span>
                  </div>
                ))}
              </div>
            </details>
          )}
          {/* 加载状态 */}
          {isLoading && (
            <div className="flex items-center gap-2 text-muted-foreground">
              <Loader2 className="h-4 w-4 animate-spin" />
              <span className="text-sm">正在处理...</span>
            </div>
          )}
        </div>
      </ScrollArea>

      {/* 输入区 */}
      <div className="flex-shrink-0 border-t bg-background p-4">
        <form onSubmit={handleSubmit} className="flex gap-2">
          <Input
            value={input}
            onChange={(e) => setInput(e.target.value)}
            placeholder="输入指令，如 查看待处理售后、订单列表..."
            disabled={isLoading}
            className="flex-1"
          />
          <Button type="submit" disabled={isLoading || !input.trim()}>
            {isLoading ? (
              <Loader2 className="h-4 w-4 animate-spin" />
            ) : (
              <Send className="h-4 w-4" />
            )}
          </Button>
        </form>
      </div>
    </div>
  );
}
