/**
 * Manus 风格 AI 入口页面
 * 简洁的大标题 + 居中输入框 + 快捷操作按钮 + 集成聊天
 */

import { useState, useEffect, useRef, useCallback } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent } from '@/components/ui/card';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Badge } from '@/components/ui/badge';
import { Textarea } from '@/components/ui/textarea';
import { supabase } from '@/integrations/supabase/client';
import { cn } from '@/lib/utils';
import { AIAgent, AI_AGENTS } from '@/types/agents';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { DynamicRenderer, type UISchema } from '@/ai/genui';
import {
  Send,
  Mic,
  MicOff,
  Plus,
  Package,
  Ticket,
  RotateCcw,
  BarChart3,
  ClipboardList,
  Sparkles,
  TrendingUp,
  AlertTriangle,
  Clock,
  Zap,
  Bot,
  ArrowRight,
  Loader2,
  User
} from 'lucide-react';
import { toast } from 'sonner';
import { 
  extractUnifiedActions, 
  executeUnifiedActions, 
  getActionLabel, 
  UnifiedAction,
} from '@/ai/unifiedActions';
import { useNavigate } from 'react-router-dom';
import { emitPageState } from './AdminAIAssistant';

interface ManusEntryPageProps {
  onNavigate?: (tab: string) => void;
}

interface QuickAction {
  id: string;
  icon: React.ReactNode;
  label: string;
  description: string;
  message: string;
  color: string;
}

interface Insight {
  id: string;
  type: 'warning' | 'success' | 'opportunity' | 'info';
  title: string;
  description: string;
  action?: string;
  timestamp: string;
}

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

const quickActions: QuickAction[] = [
  {
    id: 'inventory',
    icon: <Package className="h-4 w-4" />,
    label: '查库存',
    description: '查看库存预警',
    message: '查看当前库存预警，哪些商品需要补货？',
    color: 'text-blue-500'
  },
  {
    id: 'coupon',
    icon: <Ticket className="h-4 w-4" />,
    label: '发优惠券',
    description: '创建营销活动',
    message: '帮我创建一个新的优惠券活动',
    color: 'text-purple-500'
  },
  {
    id: 'refund',
    icon: <RotateCcw className="h-4 w-4" />,
    label: '处理退款',
    description: '查看待处理退款',
    message: '查看待处理的退款申请',
    color: 'text-rose-500'
  },
  {
    id: 'report',
    icon: <BarChart3 className="h-4 w-4" />,
    label: '查报表',
    description: '今日经营数据',
    message: '显示今日的经营报表和关键指标',
    color: 'text-emerald-500'
  },
  {
    id: 'todo',
    icon: <ClipboardList className="h-4 w-4" />,
    label: '今日待办',
    description: '查看待处理任务',
    message: '今天有哪些待处理的任务和审批？',
    color: 'text-amber-500'
  },
];

export function ManusEntryPage({ onNavigate }: ManusEntryPageProps) {
  const navigate = useNavigate();
  const [inputValue, setInputValue] = useState('');
  const [insights, setInsights] = useState<Insight[]>([]);
  const [stats, setStats] = useState({
    pendingOrders: 0,
    pendingRefunds: 0,
    lowStockProducts: 0,
    todayRevenue: 0
  });
  const [isLoading, setIsLoading] = useState(true);
  const [messages, setMessages] = useState<Message[]>([]);
  const [isSending, setIsSending] = useState(false);
  const [conversationId, setConversationId] = useState<string>('');
  const [currentAgent, setCurrentAgent] = useState<AIAgent>(AI_AGENTS.manager);
  const inputRef = useRef<HTMLInputElement>(null);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const chatContainerRef = useRef<HTMLDivElement>(null);

  // 滚动到底部
  const scrollToBottom = useCallback(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, []);

  useEffect(() => {
    scrollToBottom();
  }, [messages, scrollToBottom]);

  // 获取统计数据和洞察
  useEffect(() => {
    const fetchData = async () => {
      setIsLoading(true);
      try {
        const [ordersRes, refundsRes, productsRes, revenueRes] = await Promise.all([
          supabase.from('orders').select('id', { count: 'exact', head: true }).eq('status', 'pending'),
          supabase.from('after_sales_requests').select('id', { count: 'exact', head: true }).eq('status', 'pending'),
          supabase.from('products').select('id', { count: 'exact', head: true }).lt('stock_quantity', 10).eq('is_active', true),
          supabase.from('orders').select('total_amount').gte('created_at', new Date().toISOString().split('T')[0])
        ]);

        const todayRevenue = revenueRes.data?.reduce((sum, o) => sum + (o.total_amount || 0), 0) || 0;

        setStats({
          pendingOrders: ordersRes.count || 0,
          pendingRefunds: refundsRes.count || 0,
          lowStockProducts: productsRes.count || 0,
          todayRevenue
        });

        const newInsights: Insight[] = [];
        
        if ((refundsRes.count || 0) > 0) {
          newInsights.push({
            id: 'refunds',
            type: 'warning',
            title: `${refundsRes.count} 个退款待处理`,
            description: '有客户正在等待退款审批，建议尽快处理',
            action: '处理退款申请',
            timestamp: new Date().toISOString()
          });
        }
        
        if ((productsRes.count || 0) > 0) {
          newInsights.push({
            id: 'stock',
            type: 'warning',
            title: `${productsRes.count} 个商品库存不足`,
            description: '部分商品库存低于10件，可能影响销售',
            action: '查看库存预警',
            timestamp: new Date().toISOString()
          });
        }

        if ((ordersRes.count || 0) > 0) {
          newInsights.push({
            id: 'orders',
            type: 'info',
            title: `${ordersRes.count} 个订单待发货`,
            description: '新订单等待处理，请及时安排发货',
            action: '查看订单',
            timestamp: new Date().toISOString()
          });
        }

        if (todayRevenue > 0) {
          newInsights.push({
            id: 'revenue',
            type: 'success',
            title: `今日已收入 ¥${todayRevenue.toFixed(0)}`,
            description: '销售情况良好，继续保持！',
            timestamp: new Date().toISOString()
          });
        }

        setInsights(newInsights);
      } catch (error) {
        console.error('Failed to fetch stats:', error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchData();
  }, []);

  // 发送消息到 AI
  const sendMessage = async (message: string) => {
    if (!message.trim() || isSending) return;

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

    setMessages(prev => [...prev, userMessage]);
    setInputValue('');
    setIsSending(true);

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

      // 调用 manager-genui edge function
      const response = await supabase.functions.invoke('manager-genui', {
        body: {
          message: message,
          conversation_id: conversationId || undefined,
          agent_type: currentAgent.id,
          context: {
            current_tab: 'home',
            stats: stats
          }
        }
      });

      if (response.error) throw response.error;

      const data = response.data;
      
      // 保存 conversation_id
      if (data.conversation_id) {
        setConversationId(data.conversation_id);
      }

      // 解析响应
      const assistantMessage: Message = {
        role: 'assistant',
        content: data.response || data.answer || '',
        timestamp: new Date(),
        actions: data.actions || [],
        ui_schema: data.ui_schema
      };

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

      // 处理导航操作
      if (data.actions) {
        for (const action of data.actions) {
          if (action.type === 'navigate' && action.params?.tab) {
            onNavigate?.(action.params.tab);
          }
        }
      }

    } catch (error: any) {
      console.error('Failed to send message:', error);
      toast.error('发送失败，请重试');
      
      // 添加错误消息
      setMessages(prev => [...prev, {
        role: 'assistant',
        content: '抱歉，处理请求时出现错误，请稍后重试。',
        timestamp: new Date()
      }]);
    } finally {
      setIsSending(false);
    }
  };

  const handleSend = () => {
    sendMessage(inputValue);
  };

  const handleQuickAction = (action: QuickAction) => {
    sendMessage(action.message);
  };

  const handleInsightClick = (insight: Insight) => {
    if (insight.action) {
      sendMessage(insight.action);
    }
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  };

  const insightTypeStyles = {
    warning: 'border-l-amber-500 bg-amber-50/50 dark:bg-amber-950/20',
    success: 'border-l-emerald-500 bg-emerald-50/50 dark:bg-emerald-950/20',
    opportunity: 'border-l-blue-500 bg-blue-50/50 dark:bg-blue-950/20',
    info: 'border-l-muted-foreground bg-muted/30',
  };

  const insightTypeIcons = {
    warning: <AlertTriangle className="h-4 w-4 text-amber-500" />,
    success: <TrendingUp className="h-4 w-4 text-emerald-500" />,
    opportunity: <Zap className="h-4 w-4 text-blue-500" />,
    info: <Clock className="h-4 w-4 text-muted-foreground" />,
  };

  // 有消息时显示对话视图
  if (messages.length > 0) {
    return (
      <div className="flex flex-col h-[calc(100vh-120px)]">
        {/* 标题栏 */}
        <div className="flex items-center justify-between px-4 py-2 border-b bg-background/95 backdrop-blur">
          <div className="flex items-center gap-2">
            <Bot className="h-5 w-5 text-primary" />
            <span className="font-medium">AI 管理助理</span>
          </div>
          <Button 
            variant="ghost" 
            size="sm"
            onClick={() => setMessages([])}
            className="text-muted-foreground"
          >
            新对话
          </Button>
        </div>

        {/* 对话消息区 */}
        <ScrollArea className="flex-1 px-4 py-4" ref={chatContainerRef}>
          <div className="max-w-4xl mx-auto space-y-4">
            {messages.map((msg, idx) => (
              <div
                key={idx}
                className={cn(
                  "flex gap-3",
                  msg.role === 'user' ? "justify-end" : "justify-start"
                )}
              >
                {msg.role === 'assistant' && (
                  <Avatar className="h-8 w-8 shrink-0">
                    <AvatarFallback className="bg-primary/10 text-primary">
                      <Bot className="h-4 w-4" />
                    </AvatarFallback>
                  </Avatar>
                )}
                
                <div
                  className={cn(
                    "max-w-[80%] rounded-lg px-4 py-2",
                    msg.role === 'user' 
                      ? "bg-primary text-primary-foreground"
                      : "bg-muted"
                  )}
                >
                  {/* UI Schema 渲染 */}
                  {msg.ui_schema && (
                    <div className="mb-2">
                      <DynamicRenderer 
                        schema={msg.ui_schema} 
                        context={{ 
                          onAction: (action, params) => {
                            if (action === 'navigate' && params?.tab) {
                              onNavigate?.(params.tab);
                            }
                          }
                        }}
                      />
                    </div>
                  )}
                  
                  {/* 文本内容 */}
                  <div className="whitespace-pre-wrap text-sm">
                    {msg.content}
                  </div>
                  
                  {/* 操作按钮 */}
                  {msg.actions && msg.actions.length > 0 && (
                    <div className="flex flex-wrap gap-2 mt-2">
                      {msg.actions.map((action: any, actionIdx: number) => (
                        <Button
                          key={actionIdx}
                          variant="secondary"
                          size="sm"
                          onClick={() => {
                            if (action.type === 'navigate' && action.params?.tab) {
                              onNavigate?.(action.params.tab);
                            }
                          }}
                        >
                          {action.label || action.type}
                        </Button>
                      ))}
                    </div>
                  )}
                  
                  <p className="text-xs mt-1 opacity-60">
                    {msg.timestamp.toLocaleTimeString('zh-CN', {
                      hour: '2-digit',
                      minute: '2-digit'
                    })}
                  </p>
                </div>

                {msg.role === 'user' && (
                  <Avatar className="h-8 w-8 shrink-0">
                    <AvatarFallback className="bg-secondary">
                      <User className="h-4 w-4" />
                    </AvatarFallback>
                  </Avatar>
                )}
              </div>
            ))}
            
            {isSending && (
              <div className="flex justify-start gap-3">
                <Avatar className="h-8 w-8 shrink-0">
                  <AvatarFallback className="bg-primary/10 text-primary">
                    <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>
            )}
            
            <div ref={messagesEndRef} />
          </div>
        </ScrollArea>

        {/* 输入区域 */}
        <div className="border-t bg-background p-4">
          <div className="max-w-4xl mx-auto flex gap-2">
            <Input
              ref={inputRef}
              value={inputValue}
              onChange={(e) => setInputValue(e.target.value)}
              onKeyDown={handleKeyPress}
              placeholder="继续对话..."
              className="flex-1"
              disabled={isSending}
            />
            <Button 
              onClick={handleSend}
              disabled={!inputValue.trim() || isSending}
            >
              {isSending ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : (
                <Send className="h-4 w-4" />
              )}
            </Button>
          </div>
        </div>
      </div>
    );
  }

  // 无消息时显示欢迎页
  return (
    <div className="flex flex-col items-center justify-start min-h-full py-8 px-4">
      {/* 主标题区 */}
      <div className="text-center mb-8 max-w-2xl">
        <div className="inline-flex items-center gap-2 mb-4">
          <div className="relative">
            <div className="h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center">
              <Bot className="h-6 w-6 text-primary" />
            </div>
            <span className="absolute -bottom-0.5 -right-0.5 flex h-3.5 w-3.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-3.5 w-3.5 bg-emerald-500"></span>
            </span>
          </div>
        </div>
        <h1 className="text-3xl font-semibold text-foreground mb-2">
          我能为你做什么？
        </h1>
        <p className="text-muted-foreground">
          分配一个任务或提问任何问题
        </p>
      </div>

      {/* 输入框区域 */}
      <div className="w-full max-w-2xl mb-8">
        <Card className="shadow-lg border-2 hover:border-primary/50 transition-colors">
          <CardContent className="p-4">
            <div className="flex items-center gap-3">
              <Button variant="ghost" size="icon" className="shrink-0 text-muted-foreground hover:text-foreground">
                <Plus className="h-5 w-5" />
              </Button>
              <Input
                ref={inputRef}
                value={inputValue}
                onChange={(e) => setInputValue(e.target.value)}
                onKeyDown={handleKeyPress}
                placeholder="输入你的问题或任务..."
                className="flex-1 border-0 shadow-none text-base focus-visible:ring-0 placeholder:text-muted-foreground/60"
              />
              <div className="flex items-center gap-1">
                <Button variant="ghost" size="icon" className="shrink-0 text-muted-foreground hover:text-foreground">
                  <Mic className="h-5 w-5" />
                </Button>
                <Button 
                  size="icon" 
                  onClick={handleSend}
                  disabled={!inputValue.trim() || isSending}
                  className="shrink-0"
                >
                  {isSending ? (
                    <Loader2 className="h-4 w-4 animate-spin" />
                  ) : (
                    <Send className="h-4 w-4" />
                  )}
                </Button>
              </div>
            </div>
            
            {/* Agent 连接状态 */}
            <div className="flex items-center justify-between mt-3 pt-3 border-t">
              <div className="flex items-center gap-2 text-xs text-muted-foreground">
                <Sparkles className="h-3.5 w-3.5" />
                <span>已连接 5 个智能助理</span>
              </div>
              <div className="flex items-center gap-1">
                {['店长', '财务', '商品', '营销', '客服'].map((name) => (
                  <Badge 
                    key={name} 
                    variant="secondary" 
                    className="text-[10px] px-1.5 py-0"
                  >
                    {name}
                  </Badge>
                ))}
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* 快捷操作按钮 */}
      <div className="flex flex-wrap justify-center gap-2 mb-8 max-w-2xl">
        {quickActions.map((action) => (
          <Button
            key={action.id}
            variant="outline"
            className="h-9 gap-2 hover:bg-muted/80 transition-colors"
            onClick={() => handleQuickAction(action)}
          >
            <span className={action.color}>{action.icon}</span>
            <span>{action.label}</span>
          </Button>
        ))}
      </div>

      {/* AI 洞察卡片 */}
      {insights.length > 0 && (
        <div className="w-full max-w-3xl">
          <div className="flex items-center gap-2 mb-3">
            <Sparkles className="h-4 w-4 text-primary" />
            <h3 className="text-sm font-medium">AI 洞察</h3>
            <Badge variant="secondary" className="text-xs">
              {insights.length}
            </Badge>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
            {insights.map((insight) => (
              <Card 
                key={insight.id}
                className={cn(
                  "border-l-4 cursor-pointer hover:shadow-md transition-shadow",
                  insightTypeStyles[insight.type]
                )}
                onClick={() => handleInsightClick(insight)}
              >
                <CardContent className="p-4">
                  <div className="flex items-start gap-3">
                    <div className="shrink-0 mt-0.5">
                      {insightTypeIcons[insight.type]}
                    </div>
                    <div className="flex-1 min-w-0">
                      <h4 className="text-sm font-medium truncate">{insight.title}</h4>
                      <p className="text-xs text-muted-foreground mt-1 line-clamp-2">
                        {insight.description}
                      </p>
                      {insight.action && (
                        <Button 
                          variant="link" 
                          className="h-auto p-0 mt-2 text-xs text-primary"
                          onClick={(e) => {
                            e.stopPropagation();
                            handleInsightClick(insight);
                          }}
                        >
                          {insight.action}
                          <ArrowRight className="h-3 w-3 ml-1" />
                        </Button>
                      )}
                    </div>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </div>
      )}

      {/* 统计摘要 */}
      <div className="w-full max-w-3xl mt-8">
        <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
          <StatCard
            icon={<ClipboardList className="h-4 w-4" />}
            label="待发货订单"
            value={stats.pendingOrders}
            color="text-blue-500"
            onClick={() => onNavigate?.('transactions')}
          />
          <StatCard
            icon={<RotateCcw className="h-4 w-4" />}
            label="待处理退款"
            value={stats.pendingRefunds}
            color="text-rose-500"
            onClick={() => onNavigate?.('aftersales')}
          />
          <StatCard
            icon={<Package className="h-4 w-4" />}
            label="库存预警"
            value={stats.lowStockProducts}
            color="text-amber-500"
            onClick={() => onNavigate?.('products')}
          />
          <StatCard
            icon={<TrendingUp className="h-4 w-4" />}
            label="今日收入"
            value={`¥${stats.todayRevenue.toFixed(0)}`}
            color="text-emerald-500"
            onClick={() => onNavigate?.('transactions')}
          />
        </div>
      </div>
    </div>
  );
}

// 统计卡片组件
function StatCard({ 
  icon, 
  label, 
  value, 
  color,
  onClick 
}: { 
  icon: React.ReactNode; 
  label: string; 
  value: number | string; 
  color: string;
  onClick?: () => void;
}) {
  return (
    <Card 
      className="cursor-pointer hover:shadow-md transition-shadow"
      onClick={onClick}
    >
      <CardContent className="p-4">
        <div className="flex items-center gap-2 mb-2">
          <span className={color}>{icon}</span>
          <span className="text-xs text-muted-foreground">{label}</span>
        </div>
        <p className="text-xl font-semibold">{value}</p>
      </CardContent>
    </Card>
  );
}

export default ManusEntryPage;
