import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Copy, ThumbsUp, ThumbsDown, Bot, User, Package, ShoppingCart } from "lucide-react";
import { AfterSalesProgressCard } from "./AfterSalesProgressCard";
import { AfterSalesStatusDisplay } from "./AfterSalesStatusDisplay";
import { ProductCard } from "./ProductCard";
import { AgentIntroCard } from "./AgentIntroCard";
import { CouponCard } from "./CouponCard";
import { cn } from "@/lib/utils";
import { PLACEHOLDER_PRODUCT_SMALL } from "@/utils/placeholderImage";

export interface Message {
  id: string;
  content: string;
  sender: 'user' | 'ai';
  timestamp: string;
  type?: 'text' | 'product' | 'products' | 'order' | 'aftersales' | 'agent_intro' | 'transactions' | 'dify_order' | 'coupon';
  agent?: {
    id: string;
    name: string;
    avatar: string;
    role: string;
    color: string;
  };
  metadata?: {
    productInfo?: {
      name: string;
      price: string;
      image: string;
      status: string;
    };
    productsInfo?: Array<{
      id: string;
      name: string;
      price: number;
      image: string;
      status: string;
      category: string;
      stock_quantity: number;
    }>;
    orderInfo?: Array<{
      orderId: string;
      orderUuid: string;
      status: string;
      items: Array<{ name: string; quantity: number; price: string; productId: string }>;
      total: string;
      orderDate?: string;
      shippingAddress?: string;
    }>;
    afterSalesInfo?: Array<{
      id: string;
      orderNumber: string;
      productName: string;
      productImage: string;
      type: 'return' | 'exchange' | 'repair';
      status: 'pending' | 'approved' | 'processing' | 'shipped' | 'completed' | 'rejected';
      progress: number;
      currentStep: string;
      createdAt: string;
      estimatedCompletion?: string;
      trackingNumber?: string;
      amount?: number;
    }>;
    transactionInfo?: Array<{
      id: string;
      orderNumber: string;
      productName: string;
      productImage: string;
      quantity: number;
      price: number;
      status: string;
      progress: number;
      currentStep: string;
      createdAt: string;
      estimatedDelivery?: string;
      trackingNumber?: string;
      paymentMethod?: string;
      shippingAddress?: string;
      totalAmount: number;
    }>;
    agentSwitchInfo?: {
      currentAgent: any;
      newAgent: any;
    };
    agentIntroInfo?: {
      agent: any;
    };
    imageInfo?: {
      url: string;
      name: string;
      size: number;
    };
    couponInfo?: {
      id: string;
      code: string;
      name: string;
      description?: string;
      type: string;
      discount_value: number;
      min_purchase_amount?: number;
      max_discount_amount?: number;
      end_date: string;
      scope: string;
    };
    // ✅ 添加 highlights 和 comparison 用于产品比较显示
    highlights?: string[];
    comparison?: string;
  };
}

interface ChatMessageProps {
  message: Message;
  showAvatar?: boolean;
  onCopy?: (content: string) => void;
  onFeedback?: (messageId: string, type: 'up' | 'down') => void;
  onAddToCart?: (product: any) => void;
  onViewDetails?: (productId: string) => void;
  onViewAfterSalesDetails?: (afterSalesId: string) => void;
  onContactAfterSalesService?: (afterSalesId: string) => void;
  onAgentSwitch?: (newAgentId: string) => void;
  onCancelAgentSwitch?: () => void;
  onViewOrderDetails?: (orderId: string) => void;
  onTrackOrder?: (orderId: string) => void;
  onRateOrder?: (orderId: string) => void;
  onRefundOrder?: (orderId: string) => void;
  compact?: boolean; // 紧凑模式，用于shop页面的小窗口
}

export function ChatMessage({ 
  message, 
  showAvatar = true,
  onCopy, 
  onFeedback, 
  onAddToCart, 
  onViewDetails, 
  onViewAfterSalesDetails, 
  onContactAfterSalesService,
  onAgentSwitch,
  onCancelAgentSwitch,
  onViewOrderDetails,
  onTrackOrder,
  onRateOrder,
  onRefundOrder,
  compact = false
}: ChatMessageProps) {
  const isUser = message.sender === 'user';

  const handleCopy = () => {
    if (onCopy) {
      onCopy(message.content);
    }
  };

  const renderProductInfo = () => {
    if (!message.metadata?.productInfo) return null;
    
    const { productInfo } = message.metadata;
    
    return (
      <Card className="mt-3 p-4 bg-card border-border hover:shadow-md transition-shadow">
        <div className="flex items-start space-x-4">
          <div className="w-20 h-20 bg-muted rounded-lg overflow-hidden">
            {productInfo.image ? (
              <img 
                src={productInfo.image} 
                alt={productInfo.name}
                className="w-full h-full object-cover"
                onError={(e) => {
                  e.currentTarget.src = PLACEHOLDER_PRODUCT_SMALL;
                }}
              />
            ) : (
              <div className="w-full h-full flex items-center justify-center">
                <Package className="h-8 w-8 text-muted-foreground" />
              </div>
            )}
          </div>
          <div className="flex-1">
            <h4 className="font-semibold text-foreground mb-1">{productInfo.name}</h4>
            <p className="text-xl font-bold text-primary mb-2">{productInfo.price}</p>
            <div className="flex items-center gap-2 mb-3">
              <Badge variant="secondary">
                {productInfo.status}
              </Badge>
            </div>
            <div className="flex gap-2">
              <Button size="sm" variant="outline" className="flex-1">
                查看详情
              </Button>
              <Button size="sm" className="flex-1">
                <ShoppingCart className="w-4 h-4 mr-1" />
                加入购物车
              </Button>
            </div>
          </div>
        </div>
      </Card>
    );
  };

  const renderProductsInfo = () => {
    if (!message.metadata?.productsInfo) return null;
    
    const { productsInfo } = message.metadata;
    console.log('ChatMessage: productsInfo data:', productsInfo);
    
    // 紧凑模式：使用竖向列表布局，适用于窄窗口
    if (compact) {
      return (
        <div className="mt-3 space-y-2 max-w-full">
          {productsInfo.map((product) => {
            const isInStock = (product.stock_quantity || 0) > 0;
            return (
              <Card 
                key={product.id}
                className="w-full bg-card hover:shadow-md transition-all duration-200 cursor-pointer"
                onClick={() => onViewDetails?.(product.id)}
              >
                <CardContent className="p-2">
                  <div className="flex gap-2">
                    <div className="w-16 h-16 bg-muted rounded-lg flex-shrink-0 overflow-hidden">
                      <img 
                        src={product.image || PLACEHOLDER_PRODUCT_SMALL} 
                        alt={product.name}
                        className="w-full h-full object-cover"
                        onError={(e) => {
                          e.currentTarget.src = PLACEHOLDER_PRODUCT_SMALL;
                        }}
                      />
                    </div>
                    <div className="flex-1 min-w-0 flex flex-col justify-between">
                      <div>
                        <h4 className="text-xs font-medium text-foreground line-clamp-2 mb-1">
                          {product.name.replace(/^识别商品：/, '')}
                        </h4>
                        {product.category && (
                          <Badge variant="secondary" className="text-[10px] px-1.5 py-0 h-4">
                            {product.category}
                          </Badge>
                        )}
                      </div>
                      <div className="flex items-center justify-between mt-1">
                        <span className="text-red-600 font-bold text-sm">
                          ¥{product.price.toFixed(2)}
                        </span>
                        <Button
                          size="sm"
                          variant="default"
                          className="h-6 px-2 text-[10px] bg-red-600 hover:bg-red-700"
                          disabled={!isInStock}
                          onClick={(e) => {
                            e.stopPropagation();
                            onAddToCart?.({
                              id: product.id,
                              name: product.name,
                              price: product.price,
                              image_url: product.image,
                              category: product.category,
                              stock_quantity: product.stock_quantity || 0
                            });
                          }}
                        >
                          {isInStock ? '加购' : '缺货'}
                        </Button>
                      </div>
                    </div>
                  </div>
                </CardContent>
              </Card>
            );
          })}
        </div>
      );
    }
    
    // 默认模式：使用网格布局，适用于宽屏
    return (
      <div className="mt-3 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 animate-fade-in">
        {productsInfo.map((product) => {
          console.log('ChatMessage: Individual product before ProductCard:', product);
          console.log('ChatMessage: stock_quantity value:', product.stock_quantity);
          
          return (
            <ProductCard
              key={product.id}
              product={{
                id: product.id,
                name: product.name,
                price: product.price,
                image_url: product.image,
                category: product.category,
                stock_quantity: product.stock_quantity || 0
              }}
              onAddToCart={onAddToCart}
              onViewDetails={onViewDetails}
            />
          );
        })}
      </div>
    );
  };

  const renderOrderInfo = () => {
    if (!message.metadata?.orderInfo || !Array.isArray(message.metadata.orderInfo)) return null;
    
    const { orderInfo } = message.metadata;
    
    return (
      <div className="mt-3 space-y-3">
        {orderInfo.map((order, index) => (
          <Card key={index} className="p-4 bg-card border-border hover:shadow-md transition-shadow">
            {/* 订单头部信息 */}
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center space-x-2">
                <ShoppingCart className="h-5 w-5 text-primary" />
                <span className="font-semibold text-foreground">订单 #{order.orderId}</span>
                {order.status && (
                  <Badge variant={
                    order.status === '已发货' || order.status === 'shipped' ? 'default' :
                    order.status === '已完成' || order.status === 'completed' ? 'secondary' :
                    order.status === '待支付' || order.status === 'pending' ? 'outline' :
                    'secondary'
                  }>
                    {order.status}
                  </Badge>
                )}
              </div>
              {order.total && (
                <div className="text-right">
                  <div className="text-sm text-muted-foreground">总计</div>
                  <div className="font-bold text-lg text-primary">{order.total}</div>
                </div>
              )}
            </div>
            
            {/* 商品列表 */}
            {order.items && order.items.length > 0 && (
              <div className="space-y-3">
                <div className="text-sm font-medium text-muted-foreground border-b border-border pb-2">
                  商品详情
                </div>
                {order.items.map((item, itemIndex) => (
                  <div key={itemIndex} className="bg-muted/30 rounded-lg p-3">
                    <div className="flex justify-between items-start mb-2">
                      <div className="flex-1">
                        <div className="font-medium text-foreground">{item.name}</div>
                        <div className="text-sm text-muted-foreground">数量：{item.quantity}</div>
                      </div>
                      <div className="text-right">
                        <div className="font-medium text-foreground">{item.price}</div>
                      </div>
                    </div>
                    <div className="flex gap-2">
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => onViewDetails?.(item.productId)}
                        className="text-xs h-7 flex-1"
                      >
                        商品详情
                      </Button>
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => onContactAfterSalesService?.(`order_${order.orderUuid}`)}
                        className="text-xs h-7 flex-1 text-orange-600 border-orange-200 hover:bg-orange-50 dark:hover:bg-orange-950"
                      >
                        退换货
                      </Button>
                    </div>
                  </div>
                ))}
              </div>
            )}
            
            {/* 订单详细信息 */}
            <div className="mt-4 space-y-2 text-sm">
              {order.orderDate && (
                <div className="flex justify-between">
                  <span className="text-muted-foreground">下单时间：</span>
                  <span className="text-foreground">{order.orderDate}</span>
                </div>
              )}
              {order.shippingAddress && (
                <div className="flex justify-between">
                  <span className="text-muted-foreground">配送地址：</span>
                  <span className="text-foreground max-w-64 text-right">{order.shippingAddress}</span>
                </div>
              )}
            </div>
            
            {/* 订单操作按钮 */}
            <div className="mt-4 flex gap-2">
              <Button
                size="sm"
                variant="outline"
                onClick={() => onViewOrderDetails?.(order.orderUuid)}
                className="flex-1"
              >
                查看详情
              </Button>
              {(order.status === '已发货' || order.status === 'shipped') && (
                <Button
                  size="sm"
                  variant="outline"
                  onClick={() => onTrackOrder?.(order.orderUuid)}
                  className="flex-1"
                >
                  物流跟踪
                </Button>
              )}
              {(order.status === '已完成' || order.status === 'completed') && (
                <Button
                  size="sm"
                  variant="outline"
                  onClick={() => onRateOrder?.(order.orderUuid)}
                  className="flex-1"
                >
                  评价订单
                </Button>
              )}
            </div>
          </Card>
        ))}
      </div>
    );
  };

  const renderAfterSalesInfo = () => {
    if (!message.metadata?.afterSalesInfo) return null;
    
    return (
      <div className="mt-3">
        <AfterSalesStatusDisplay 
          requests={message.metadata.afterSalesInfo}
          onViewDetails={onViewAfterSalesDetails}
          onContactService={onContactAfterSalesService}
        />
      </div>
    );
  };


  const renderAgentIntroInfo = () => {
    if (!message.metadata?.agentIntroInfo) return null;
    
    return (
      <div className="mt-3">
        <AgentIntroCard agent={message.metadata.agentIntroInfo.agent} />
      </div>
    );
  };

  const renderCouponInfo = () => {
    if (!message.metadata?.couponInfo) return null;
    
    return (
      <div className="mt-3">
        <CouponCard coupon={message.metadata.couponInfo} />
      </div>
    );
  };

  // 含商品/订单等富卡片时，去掉外层气泡，避免双层边框
  const hasRichCards = !isUser && !!(
    message.metadata?.productInfo ||
    message.metadata?.productsInfo ||
    message.metadata?.orderInfo ||
    message.metadata?.afterSalesInfo ||
    message.metadata?.agentIntroInfo ||
    message.metadata?.couponInfo
  );

  return (
    <div className={cn(
      "group p-4 message-enter",
      isUser ? "text-right" : "text-left"
    )}>
      {/* Message Bubble */}
      <div className={cn(
        "inline-block max-w-[80%] text-sm leading-relaxed space-y-3",
        isUser
          ? "bg-user text-user-foreground rounded-2xl px-4 py-3 ml-auto"
          : hasRichCards
            ? "text-foreground"
            : "bg-surface border border-border rounded-2xl px-4 py-3 text-foreground"
      )}>
        {/* Message Content - 处理 \n\n 换行符 */}
        {message.content && (
          <p className="whitespace-pre-wrap">
            {message.content.split('\\n\\n').join('\n\n').split('\\n').join('\n')}
          </p>
        )}
        
        {/* Image Display */}
        {message.metadata?.imageInfo && (
          <div className="mt-3">
            <img 
              src={message.metadata.imageInfo.url} 
              alt={message.metadata.imageInfo.name}
              className="max-w-sm max-h-64 rounded-lg border border-border object-cover"
            />
            <p className="text-xs text-muted-foreground mt-1">
              {message.metadata.imageInfo.name} ({(message.metadata.imageInfo.size / 1024 / 1024).toFixed(2)} MB)
            </p>
          </div>
        )}
        
        {/* Product/Order Info */}
        {!isUser && (
          <>
            {renderProductInfo()}
            {renderProductsInfo()}
            {renderOrderInfo()}
            {renderAfterSalesInfo()}
            {renderAgentIntroInfo()}
            {renderCouponInfo()}
            
            {/* ✅ 显示对比分析卡片（comparison优先，有comparison时不再单独显示highlights避免重复） */}
            {message.metadata?.comparison ? (
              <div className="mt-3">
                <div className="bg-blue-50 dark:bg-blue-950/30 border border-blue-200 dark:border-blue-800 rounded-lg p-3">
                  <div className="flex items-start space-x-2">
                    <div className="w-5 h-5 bg-blue-500 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5">
                      <span className="text-white text-xs">⚖️</span>
                    </div>
                    <div className="flex-1">
                      <p className="text-xs font-medium text-blue-700 dark:text-blue-300 mb-1">对比分析</p>
                      <p className="text-sm text-blue-900 dark:text-blue-100 leading-relaxed">{message.metadata.comparison}</p>
                    </div>
                  </div>
                </div>
              </div>
            ) : message.metadata?.highlights && message.metadata.highlights.length > 0 ? (
              /* 只有在没有comparison时才显示highlights，避免信息重复 */
              <div className="mt-3">
                <div className="bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-800 rounded-lg p-3">
                  <div className="flex items-start space-x-2">
                    <div className="w-5 h-5 bg-amber-500 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5">
                      <span className="text-white text-xs">💡</span>
                    </div>
                    <div className="flex-1">
                      <p className="text-xs font-medium text-amber-700 dark:text-amber-300 mb-1">重点信息</p>
                      <ul className="text-sm text-amber-900 dark:text-amber-100 space-y-1">
                        {message.metadata.highlights.map((h: string, i: number) => (
                          <li key={i}>• {h}</li>
                        ))}
                      </ul>
                    </div>
                  </div>
                </div>
              </div>
            ) : null}
          </>
        )}
      </div>

      {/* Message Actions */}
      {!isUser && (
        <div className={cn(
          "flex items-center space-x-2 opacity-0 group-hover:opacity-100 transition-opacity mt-2",
          isUser ? "justify-end" : "justify-start"
        )}>
          <Button
            variant="ghost"
            size="sm"
            onClick={handleCopy}
            className="h-7 px-2 text-muted-foreground hover:text-foreground"
          >
            <Copy className="h-3 w-3" />
          </Button>
          <Button
            variant="ghost"
            size="sm"
            onClick={() => onFeedback?.(message.id, 'up')}
            className="h-7 px-2 text-muted-foreground hover:text-success"
          >
            <ThumbsUp className="h-3 w-3" />
          </Button>
          <Button
            variant="ghost"
            size="sm"
            onClick={() => onFeedback?.(message.id, 'down')}
            className="h-7 px-2 text-muted-foreground hover:text-destructive"
          >
            <ThumbsDown className="h-3 w-3" />
          </Button>
        </div>
      )}

      {/* Timestamp */}
      <div className={cn(
        "text-xs text-muted-foreground mt-1",
        isUser ? "text-right" : "text-left"
      )}>
        {message.timestamp}
      </div>
    </div>
  );
}