/**
 * 已选产品列表组件
 * 作者: 阿瑞
 * 功能: 展示和管理已选择的产品列表
 * 版本: 1.1.0
 */

'use client';

import React from 'react';
import { Card, List, Avatar, Typography, Button, Statistic, Tag, Badge, Empty, InputNumber, Space } from 'antd';
import { DeleteOutlined, ShoppingOutlined, TagOutlined, ShopOutlined, PlusOutlined } from '@ant-design/icons';

// 产品详情接口，包含更多产品信息
interface ProductItemDetail {
  productId: number;
  name: string;
  price: number;
  quantity: number;
  total: number;
  image?: string;
  supplierName?: string;
  brandName?: string;
  code?: string;
  sku?: string;
  stock?: number;
}

interface SelectedProductProps {
  products: ProductItemDetail[];
  onRemove: (index: number) => void;
  onUpdateQuantity?: (index: number, quantity: number) => void; // 新增更新数量的回调
}

/**
 * 已选产品列表组件
 */
export default function SelectedProductList({
  products,
  onRemove,
  onUpdateQuantity
}: SelectedProductProps) {
  const { Text } = Typography;

  /**
   * 格式化金额显示
   */
  const formatAmount = (amount: number | string | undefined | null) => {
    if (amount === undefined || amount === null) return "0.00";
    // 确保amount是数字类型
    const numAmount = typeof amount === 'string' ? parseFloat(amount) : Number(amount);
    // 检查是否为有效数字
    if (isNaN(numAmount)) return "0.00";
    return numAmount.toFixed(2);
  };

  /**
   * 处理数量变更
   */
  const handleQuantityChange = (index: number, value: number | null) => {
    if (onUpdateQuantity && value && value > 0) {
      onUpdateQuantity(index, value);
    }
  };

  // 计算总金额
  const totalAmount = products.reduce((sum, product) => sum + product.total, 0);

  // 如果没有选择产品，则显示提示信息
  if (products.length === 0) {
    return (
      <Card
        title="已选择产品"
        variant="outlined"
        style={{ minHeight: '380px' }}  // 设定Card最小高度，确保无论是否选择产品，卡片高度保持一致
        extra={
          <Button type="primary" icon={<PlusOutlined />}
            //onClick={onAddProductClick}
          >
            新增产品
          </Button>
        }
      >
        <Empty
          image={Empty.PRESENTED_IMAGE_SIMPLE}
          description="暂未选择产品，请先添加产品"
        />
      </Card>
    );
  }

  return (
    <Card
      title={
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <ShoppingOutlined style={{ marginRight: 8 }} />
          <span>已选择产品</span>
          <Badge count={products.length} style={{ marginLeft: 8, backgroundColor: '#52c41a' }} />
        </div>
      }
      variant="outlined"
    >
      <List
        itemLayout="horizontal"
        dataSource={products}
        renderItem={(product, index) => (
          <List.Item
            key={`${product.productId}-${index}`}
            actions={[
              <>
                <div style={{ width: 100, textAlign: 'center' }}>
                  <Text type="secondary">数量</Text>
                  <div>
                    <InputNumber
                      min={1}
                      value={product.quantity}
                      onChange={(value) => handleQuantityChange(index, value)}
                      style={{ width: 80 }}
                      size="small"
                    />
                  </div>
                </div>
              </>,
              <>
                <div style={{ width: 80, textAlign: 'center' }}>
                  <Text type="secondary">小计</Text>
                  <div>
                    <Text strong style={{ color: '#f50' }}>
                      ¥{formatAmount(product.total)}
                    </Text>
                  </div>
                </div>
              </>,
              <Button
                type="text"
                danger
                icon={<DeleteOutlined />}
                onClick={() => onRemove(index)}
              />
            ]}
          >
            <List.Item.Meta
              avatar={
                <Avatar
                  shape="square"
                  size={64}
                  src={product.image || '/images/product-placeholder.png'}
                  style={{ borderRadius: 4 }}
                  onError={() => {
                    // Ant Design Avatar 的 onError 需要返回一个布尔值
                    // 返回 true 以使用默认 fallback 行为
                    return true;
                  }}
                />
              }
              title={
                <Space direction="vertical" size={0} style={{ width: '100%' }}>
                  <Text strong>{product.name}</Text>
                  <Space size={4}>
                    {product.code && (
                      <Tag color="blue" icon={<TagOutlined />}>{product.code}</Tag>
                    )}
                    {product.supplierName && (
                      <Tag color="green" icon={<ShopOutlined />}>{product.supplierName}</Tag>
                    )}
                    {product.brandName && (
                      <Tag color="purple">{product.brandName}</Tag>
                    )}
                  </Space>
                </Space>
              }
              description={
                <div>
                  <Text type="secondary">单价: </Text>
                  <Text type="danger">¥{formatAmount(product.price)}</Text>
                </div>
              }
            />
          </List.Item>
        )}
        footer={
          <div style={{ textAlign: 'right', padding: '12px 0' }}>
            <Space align="center" size="large">
              <Text>合计 {products.length} 件商品</Text>
              <Statistic
                title="总金额"
                value={totalAmount}
                precision={2}
                prefix="¥"
                valueStyle={{ color: '#f50', fontSize: '18px' }}
              />
            </Space>
          </div>
        }
      />
    </Card>
  );
} 