import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { Separator } from "@/components/ui/separator";
import { 
  Package, 
  Truck, 
  CheckCircle2, 
  Clock, 
  AlertCircle, 
  CreditCard, 
  MapPin,
  MessageCircle,
  Star,
  RefreshCw,
  Eye
} from "lucide-react";
import { cn } from "@/lib/utils";
import { PLACEHOLDER_PRODUCT_SMALL } from "@/utils/placeholderImage";

interface TransactionItem {
  id: string;
  orderNumber: string;
  productName: string;
  productImage: string;
  quantity: number;
  price: number;
  status: 'pending' | 'confirmed' | 'paid' | 'shipped' | 'delivered' | 'cancelled' | 'refunded';
  progress: number;
  currentStep: string;
  createdAt: string;
  estimatedDelivery?: string;
  trackingNumber?: string;
  paymentMethod?: string;
  shippingAddress?: string;
  totalAmount: number;
}

interface TransactionStatusCardProps {
  transactions: TransactionItem[];
  onViewDetails?: (transactionId: string) => void;
  onTrackOrder?: (transactionId: string) => void;
  onContactService?: (transactionId: string) => void;
  onRateOrder?: (transactionId: string) => void;
  onRefund?: (transactionId: string) => void;
}

const statusConfig = {
  pending: {
    label: '待付款',
    color: 'bg-yellow-100 text-yellow-800 border-yellow-200',
    icon: Clock,
    description: '请尽快完成付款'
  },
  confirmed: {
    label: '已确认',
    color: 'bg-blue-100 text-blue-800 border-blue-200',
    icon: CheckCircle2,
    description: '订单已确认，正在准备发货'
  },
  paid: {
    label: '已付款',
    color: 'bg-green-100 text-green-800 border-green-200',
    icon: CreditCard,
    description: '付款成功，正在处理订单'
  },
  shipped: {
    label: '已发货',
    color: 'bg-purple-100 text-purple-800 border-purple-200',
    icon: Truck,
    description: '商品正在配送中'
  },
  delivered: {
    label: '已送达',
    color: 'bg-emerald-100 text-emerald-800 border-emerald-200',
    icon: Package,
    description: '订单已完成'
  },
  cancelled: {
    label: '已取消',
    color: 'bg-muted text-foreground border-border',
    icon: AlertCircle,
    description: '订单已取消'
  },
  refunded: {
    label: '已退款',
    color: 'bg-red-100 text-red-800 border-red-200',
    icon: RefreshCw,
    description: '退款已处理'
  }
};

export function TransactionStatusCard({ 
  transactions, 
  onViewDetails, 
  onTrackOrder, 
  onContactService, 
  onRateOrder,
  onRefund 
}: TransactionStatusCardProps) {
  if (!transactions || transactions.length === 0) {
    return (
      <Card className="w-full">
        <CardContent className="flex flex-col items-center justify-center py-12">
          <Package className="h-16 w-16 text-muted-foreground mb-4" />
          <h3 className="text-lg font-semibold text-foreground mb-2">暂无交易记录</h3>
          <p className="text-muted-foreground text-center">
            您还没有任何订单，快去选购喜欢的商品吧！
          </p>
        </CardContent>
      </Card>
    );
  }

  return (
    <div className="space-y-4">
      {transactions.map((transaction) => {
        const statusInfo = statusConfig[transaction.status];
        const StatusIcon = statusInfo.icon;

        return (
          <Card key={transaction.id} className="w-full hover:shadow-md transition-shadow">
            <CardHeader className="pb-3">
              <div className="flex items-center justify-between">
                <CardTitle className="text-lg flex items-center gap-2">
                  <StatusIcon className="h-5 w-5" />
                  订单 #{transaction.orderNumber}
                </CardTitle>
                <Badge className={cn("border", statusInfo.color)}>
                  {statusInfo.label}
                </Badge>
              </div>
              <p className="text-sm text-muted-foreground">
                {statusInfo.description} • {transaction.createdAt}
              </p>
            </CardHeader>

            <CardContent className="space-y-4">
              {/* 商品信息 */}
              <div className="flex items-start gap-4">
                <div className="w-20 h-20 bg-muted rounded-lg overflow-hidden flex-shrink-0">
                  <img
                    src={transaction.productImage || PLACEHOLDER_PRODUCT_SMALL}
                    alt={transaction.productName}
                    className="w-full h-full object-cover"
                    onError={(e) => {
                      e.currentTarget.src = PLACEHOLDER_PRODUCT_SMALL;
                    }}
                  />
                </div>
                
                <div className="flex-1 min-w-0">
                  <h4 className="font-semibold text-foreground mb-1 truncate">
                    {transaction.productName}
                  </h4>
                  <div className="flex items-center justify-between text-sm text-muted-foreground mb-2">
                    <span>数量：{transaction.quantity}</span>
                    <span>单价：¥{transaction.price.toFixed(2)}</span>
                  </div>
                  
                  {/* 进度条 */}
                  <div className="space-y-2">
                    <div className="flex items-center justify-between text-xs">
                      <span className="text-muted-foreground">{transaction.currentStep}</span>
                      <span className="font-medium">{transaction.progress}%</span>
                    </div>
                    <Progress value={transaction.progress} className="h-2" />
                  </div>
                </div>
              </div>

              {/* 订单详情 */}
              <div className="space-y-3">
                <Separator />
                
                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div>
                    <span className="text-muted-foreground">订单金额：</span>
                    <span className="font-semibold text-primary">¥{transaction.totalAmount.toFixed(2)}</span>
                  </div>
                  {transaction.paymentMethod && (
                    <div>
                      <span className="text-muted-foreground">支付方式：</span>
                      <span>{transaction.paymentMethod}</span>
                    </div>
                  )}
                </div>

                {transaction.trackingNumber && (
                  <div className="p-3 bg-primary/5 rounded-lg">
                    <div className="flex items-center gap-2 text-sm">
                      <Truck className="h-4 w-4 text-primary" />
                      <span className="text-muted-foreground">快递单号：</span>
                      <span className="font-mono">{transaction.trackingNumber}</span>
                    </div>
                  </div>
                )}

                {transaction.estimatedDelivery && (
                  <div className="flex items-center gap-2 text-sm text-muted-foreground">
                    <Clock className="h-4 w-4" />
                    <span>预计送达：{transaction.estimatedDelivery}</span>
                  </div>
                )}

                {transaction.shippingAddress && (
                  <div className="flex items-start gap-2 text-sm text-muted-foreground">
                    <MapPin className="h-4 w-4 mt-0.5 flex-shrink-0" />
                    <span className="break-words">{transaction.shippingAddress}</span>
                  </div>
                )}
              </div>

              <Separator />

              {/* 操作按钮 */}
              <div className="flex flex-wrap gap-2">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => onViewDetails?.(transaction.id)}
                  className="flex-1 sm:flex-none"
                >
                  <Eye className="w-4 h-4 mr-2" />
                  查看详情
                </Button>

                {transaction.status === 'shipped' && (
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => onTrackOrder?.(transaction.id)}
                    className="flex-1 sm:flex-none"
                  >
                    <Truck className="w-4 h-4 mr-2" />
                    查看物流
                  </Button>
                )}

                {transaction.status === 'delivered' && (
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => onRateOrder?.(transaction.id)}
                    className="flex-1 sm:flex-none"
                  >
                    <Star className="w-4 h-4 mr-2" />
                    评价订单
                  </Button>
                )}

                {(transaction.status === 'pending' || transaction.status === 'confirmed') && (
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => onRefund?.(transaction.id)}
                    className="flex-1 sm:flex-none text-destructive border-destructive hover:bg-destructive hover:text-destructive-foreground"
                  >
                    <RefreshCw className="w-4 h-4 mr-2" />
                    申请退款
                  </Button>
                )}

                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => onContactService?.(transaction.id)}
                  className="flex-1 sm:flex-none"
                >
                  <MessageCircle className="w-4 h-4 mr-2" />
                  联系客服
                </Button>
              </div>
            </CardContent>
          </Card>
        );
      })}
    </div>
  );
}