import { useState, useRef, useEffect } from 'react';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Send, Loader2, Bot, User } from 'lucide-react';
import { supabase } from '@/integrations/supabase/client';
import { DynamicRenderer } from '@/ai/genui';
import type { UISchema, RenderContext } from '@/ai/genui/types';
import { 
  sendToFinanceAI, 
  subscribeToFinanceWorkbenchUI, 
  updateFinanceWorkbenchUI 
} from './FinanceWorkbench';

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

export function FinanceGenUIChat() {
  const [messages, setMessages] = useState<Message[]>([]);
  const [input, setInput] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const scrollRef = useRef<HTMLDivElement>(null);

  // 监听工作台发来的消息
  useEffect(() => {
    const unsubscribe = subscribeToFinanceWorkbenchUI((uiSchema) => {
      // 工作台视图变化时可以在这里处理
      console.log('Workbench UI updated:', uiSchema);
    });
    return () => { unsubscribe(); };
  }, []);

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

  const handleSend = async () => {
    if (!input.trim() || isLoading) return;

    const userMessage: Message = {
      id: `user-${Date.now()}`,
      role: 'user',
      content: input.trim(),
      timestamp: new Date()
    };

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

    try {
      const { data: { session } } = await supabase.auth.getSession();
      
      const response = await supabase.functions.invoke('finance-genui', {
        body: { message: userMessage.content },
        headers: session?.access_token ? {
          Authorization: `Bearer ${session.access_token}`
        } : undefined
      });

      if (response.error) throw response.error;

      const { message: aiMessage, ui_schema } = response.data;

      const assistantMessage: Message = {
        id: `assistant-${Date.now()}`,
        role: 'assistant',
        content: aiMessage || '好的，让我为您展示相关数据。',
        uiSchema: ui_schema,
        timestamp: new Date()
      };

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

      // 同步UI到工作台
      if (ui_schema) {
        updateFinanceWorkbenchUI(ui_schema);
      }

      // 通知工作台有新消息
      sendToFinanceAI(userMessage.content);

    } catch (error) {
      console.error('Finance GenUI error:', error);
      setMessages(prev => [...prev, {
        id: `error-${Date.now()}`,
        role: 'assistant',
        content: '抱歉，处理请求时出错了，请稍后重试。',
        timestamp: new Date()
      }]);
    } finally {
      setIsLoading(false);
    }
  };

  const handleAction = (actionId: string, data?: any) => {
    console.log('Finance action:', actionId, data);
    // 处理按钮点击等交互
    if (actionId === 'view-refunds') {
      setInput('查看待退款');
      setTimeout(() => handleSend(), 100);
    } else if (actionId === 'view-orders') {
      setInput('查看订单');
      setTimeout(() => handleSend(), 100);
    } else if (actionId === 'view-recharge') {
      setInput('查看充值记录');
      setTimeout(() => handleSend(), 100);
    }
  };

  const renderContext: RenderContext = {
    onAction: handleAction,
    loading: isLoading
  };

  return (
    <Card className="flex flex-col h-full">
      <CardContent className="flex flex-col flex-1 p-4 overflow-hidden">
        <ScrollArea className="flex-1 pr-4" ref={scrollRef}>
          <div className="space-y-4">
            {messages.length === 0 && (
              <div className="text-center py-8 text-muted-foreground">
                <Bot className="h-12 w-12 mx-auto mb-3 opacity-50" />
                <p className="text-sm">你好！我是财务AI助手</p>
                <p className="text-xs mt-1">可以帮你查看营收、管理退款、分析数据</p>
              </div>
            )}

            {messages.map((msg) => (
              <div
                key={msg.id}
                className={`flex gap-3 ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}
              >
                {msg.role === 'assistant' && (
                  <div className="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center shrink-0">
                    <Bot className="h-4 w-4 text-primary" />
                  </div>
                )}
                
                <div className={`max-w-[85%] ${msg.role === 'user' ? 'order-first' : ''}`}>
                  <div
                    className={`rounded-lg px-3 py-2 ${
                      msg.role === 'user'
                        ? 'bg-primary text-primary-foreground'
                        : 'bg-muted'
                    }`}
                  >
                    <p className="text-sm whitespace-pre-wrap">{msg.content}</p>
                  </div>

                  {msg.uiSchema && (
                    <div className="mt-3">
                      <DynamicRenderer 
                        schema={msg.uiSchema} 
                        context={renderContext}
                      />
                    </div>
                  )}
                </div>

                {msg.role === 'user' && (
                  <div className="w-8 h-8 rounded-full bg-secondary flex items-center justify-center shrink-0">
                    <User className="h-4 w-4" />
                  </div>
                )}
              </div>
            ))}

            {isLoading && (
              <div className="flex gap-3">
                <div className="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center">
                  <Bot className="h-4 w-4 text-primary" />
                </div>
                <div className="bg-muted rounded-lg px-3 py-2">
                  <Loader2 className="h-4 w-4 animate-spin" />
                </div>
              </div>
            )}
          </div>
        </ScrollArea>

        <div className="flex gap-2 mt-4 pt-4 border-t">
          <Input
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyDown={(e) => e.key === 'Enter' && !e.shiftKey && handleSend()}
            placeholder="输入问题，如：查看待退款..."
            disabled={isLoading}
            className="flex-1"
          />
          <Button onClick={handleSend} disabled={isLoading || !input.trim()} size="icon">
            {isLoading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Send className="h-4 w-4" />}
          </Button>
        </div>
      </CardContent>
    </Card>
  );
}
