/**
 * 产品选择器组件
 * 作者: 阿瑞
 * 功能: 提供产品搜索和选择功能
 * 版本: 2.0.0
 */

'use client';

import React, { useState, useEffect } from 'react';
import { Product } from '@/models/team/types/old/product';
import { Select, Spin, Typography } from 'antd';

interface ProductSelectorProps {
  teamCode: string;
  onSelectProduct: (product: Product) => void;
}

/**
 * 产品选择器组件实现 - 下拉列表版本
 */
const ProductSelector = ({
  teamCode,
  onSelectProduct
}: ProductSelectorProps) => {
  // 产品列表状态
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(false);
  
  const { Text } = Typography;
  
  /**
   * 加载产品列表
   */
  useEffect(() => {
    const loadProducts = async () => {
      if (!teamCode) return;
      
      setLoading(true);
      try {
        const response = await fetch(`/api/team/${teamCode}/products?pageSize=100`);
        
        if (response.ok) {
          const data = await response.json();
          setProducts(data.products || []);
        }
      } catch (error) {
        console.error('加载产品列表失败:', error);
      } finally {
        setLoading(false);
      }
    };
    
    loadProducts();
  }, [teamCode]);
  
  /**
   * 处理选择产品
   */
  const handleChange = (value: string) => {
    const selectedProd = products.find(p => p.id.toString() === value);
    if (selectedProd) {
      onSelectProduct(selectedProd);
    }
  };
  
  /**
   * 格式化价格显示
   */
  const formatPrice = (price: number | string | undefined | null) => {
    if (price === undefined || price === null) return "0.00";
    // 确保price是数字类型
    const numPrice = typeof price === 'string' ? parseFloat(price) : Number(price);
    // 检查是否为有效数字
    if (isNaN(numPrice)) return "0.00";
    return numPrice.toFixed(2);
  };
  
  return (
    <Select
      showSearch
      style={{ width: '100%' }}
      placeholder="选择产品..."
      optionFilterProp="children"
      notFoundContent={loading ? <Spin size="small" /> : "未找到产品"}
      filterOption={(input, option) => 
        (option?.label as string).toLowerCase().includes(input.toLowerCase())
      }
      onChange={handleChange}
      loading={loading}
      optionLabelProp="label"
      options={products.map(product => ({
        value: product.id.toString(),
        label: product.name,
        product: product
      }))}
      popupRender={menu => (
        <div style={{ maxHeight: '400px', overflow: 'auto' }}>
          {menu}
        </div>
      )}
      optionRender={(option) => {
        const product = (option.data as any).product;
        return (
          <div style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 0' }}>
            <div>
              <div style={{ fontWeight: 'bold' }}>{product.name}</div>
              <div style={{ fontSize: '12px', color: '#888' }}>
                {product.brand?.name && `品牌: ${product.brand.name}`}
                {product.code && ` | 编码: ${product.code}`}
                {!product.code && product.sku && ` | SKU: ${product.sku}`}
              </div>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end' }}>
              <Text type="success" strong>¥{formatPrice(product.price)}</Text>
              <Text type="secondary" style={{ fontSize: '12px' }}>
                {product.stock > 0 ? `库存: ${product.stock}` : "无库存"}
              </Text>
            </div>
          </div>
        );
      }}
    />
  );
}

export default ProductSelector; 