import React, { memo } from 'react';
import { ChevronDown, ChevronUp, List, Image as ImageIcon } from 'lucide-react';
import { useResponsive } from '../../hooks/useResponsive';
import type { ProductWithInventory, ProductYarnRatio, ProductInRecord } from '../../types';

interface ProductListProps {
  products: ProductWithInventory[];
  productRatios: Record<string, ProductYarnRatio[]>;
  expandedGroups: Record<string, boolean>;
  onToggleGroup: (key: string) => void;
  onViewRecords: (product: ProductWithInventory) => void;
  onViewPriceHistory: (product: ProductWithInventory) => void;
  onViewStockHistory: (product: ProductWithInventory) => void;
  onEdit: (product: ProductWithInventory) => void;
  onDelete: (id: string) => void;
}

export function ProductList({
  products,
  productRatios,
  expandedGroups,
  onToggleGroup,
  onViewRecords,
  onViewPriceHistory,
  onViewStockHistory,
  onEdit,
  onDelete
}: ProductListProps) {
  const { isMobile } = useResponsive();

  // 按名称和克重分组（优先使用 total_weight），无克重的产品直接按名称分组
  const groupProductsByNameAndWeight = () => {
    const groups: Record<string, Record<string, ProductWithInventory[]>> = {};
    products.forEach(product => {
      if (!groups[product.product_name]) {
        groups[product.product_name] = {};
      }
      const weight = product.total_weight || product.weight;
      // 如果没有克重，使用特殊标记 '__no_weight__'
      const weightKey = weight ? String(weight) : '__no_weight__';
      if (!groups[product.product_name][weightKey]) {
        groups[product.product_name][weightKey] = [];
      }
      groups[product.product_name][weightKey].push(product);
    });
    return groups;
  };

  const productGroups = groupProductsByNameAndWeight();

  if (isMobile) {
    return <ProductListMobile />;
  }

  return <ProductListDesktop />;

  function ProductListDesktop() {
    return (
      <div className="space-y-3">
        {Object.entries(productGroups).map(([productName, weightGroups]) => {
          const isNameExpanded = expandedGroups[productName];
          const allProducts = Object.values(weightGroups).flat();
          const totalInRolls = allProducts.reduce((sum, p) => sum + (p.total_in_rolls || 0), 0);
          const totalInMeters = allProducts.reduce((sum, p) => sum + (p.total_in_meters || 0), 0);
          const totalOutRolls = allProducts.reduce((sum, p) => sum + (p.total_out_rolls || 0), 0);
          const totalOutMeters = allProducts.reduce((sum, p) => sum + (p.total_out_meters || 0), 0);
          const availableRolls = allProducts.reduce((sum, p) => sum + (p.raw_fabric_rolls || 0), 0);
          const availableMeters = allProducts.reduce((sum, p) => sum + (p.raw_fabric_meters || 0), 0);
          const weightCount = Object.keys(weightGroups).length;

          return (
            <div
              key={productName}
              className="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden"
            >
              {/* 一级分组头部 */}
              <div
                onClick={() => onToggleGroup(productName)}
                className="flex items-center justify-between p-4 cursor-pointer hover:bg-gray-50"
              >
                <div className="flex items-center gap-3">
                  <div className={`w-8 h-8 rounded-lg flex items-center justify-center ${isNameExpanded ? 'bg-amber-100' : 'bg-gray-100'}`}>
                    {isNameExpanded ? <ChevronUp size={18} className="text-amber-600" /> : <ChevronDown size={18} className="text-gray-500" />}
                  </div>
                  <div>
                    <h3 className="font-semibold text-gray-900">{productName}</h3>
                    <p className="text-sm text-gray-500">
                      {weightCount}个克重 · {allProducts.length}个规格 · 入库{totalInRolls}匹/件/{totalInMeters}米
                      {totalOutRolls > 0 && ` · 出库${totalOutRolls}匹/件/${totalOutMeters}米`}
                      {totalOutRolls > 0 && ` · 可用${availableRolls}匹/件/${availableMeters}米`}
                    </p>
                  </div>
                </div>
                <span className="px-2.5 py-1 bg-gray-100 text-gray-700 text-xs font-medium rounded-full">
                  {weightCount}个克重
                </span>
              </div>

              {/* 二级分组 - 使用CSS Grid实现平滑高度动画 */}
              <div
                className="border-t border-gray-100 grid transition-all duration-300 ease-out"
                style={{
                  gridTemplateRows: isNameExpanded ? '1fr' : '0fr',
                  opacity: isNameExpanded ? 1 : 0
                }}
              >
                <div className="overflow-hidden">
                  <div className="p-4 space-y-3">
                  {Object.entries(weightGroups).map(([weight, products]) => {
                    const weightKey = `${productName}-${weight}`;
                    const isWeightExpanded = expandedGroups[weightKey];
                    const hasNoWeight = weight === '__no_weight__';
                    const isSingleWeight = Object.keys(weightGroups).length === 1;

                    // 如果没有克重，直接显示产品列表
                    if (hasNoWeight) {
                      return (
                        <div key={weight} className="bg-gray-50 rounded-xl overflow-hidden">
                          <table className="w-full">
                            <thead className="bg-white/50 border-b border-gray-100">
                              <tr>
                                <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">颜色</th>
                                <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">产品码</th>
                                <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">库存</th>
                                <th className="px-3 py-2 text-right text-xs font-medium text-gray-500">操作</th>
                              </tr>
                            </thead>
                            <tbody className="divide-y divide-gray-100">
                              {products.map(product => (
                                <ProductRow
                                  key={product.id}
                                  product={product}
                                  ratios={productRatios[product.id]}
                                  onViewRecords={() => onViewRecords(product)}
                                  onViewPriceHistory={() => onViewPriceHistory(product)}
                                  onViewStockHistory={() => onViewStockHistory(product)}
                                  onEdit={() => onEdit(product)}
                                  onDelete={() => onDelete(product.id)}
                                />
                              ))}
                            </tbody>
                          </table>
                        </div>
                      );
                    }

                    // 如果只有一种克重，直接显示
                    if (isSingleWeight) {
                      return (
                        <div key={weight} className="bg-gray-50 rounded-xl overflow-hidden">
                          <div className="flex items-center gap-2 p-3 bg-gray-100 border-b border-gray-200">
                            <span className="font-medium text-gray-800">{weight}g</span>
                            {products[0]?.warp_weight && products[0]?.weft_weight && (
                              <span className="text-xs text-gray-500 ml-1">经{products[0].warp_weight}+纬{products[0].weft_weight}</span>
                            )}
                            <span className="text-xs text-gray-500">({products.length}个颜色)</span>
                          </div>
                          <table className="w-full">
                            <thead className="bg-white/50 border-b border-gray-100">
                              <tr>
                                <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">颜色</th>
                                <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">产品码</th>
                                <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">库存</th>
                                <th className="px-3 py-2 text-right text-xs font-medium text-gray-500">操作</th>
                              </tr>
                            </thead>
                            <tbody className="divide-y divide-gray-100">
                              {products.map(product => (
                                <ProductRow
                                  key={product.id}
                                  product={product}
                                  ratios={productRatios[product.id]}
                                  onViewRecords={() => onViewRecords(product)}
                                  onViewPriceHistory={() => onViewPriceHistory(product)}
                                  onViewStockHistory={() => onViewStockHistory(product)}
                                  onEdit={() => onEdit(product)}
                                  onDelete={() => onDelete(product.id)}
                                />
                              ))}
                            </tbody>
                          </table>
                        </div>
                      );
                    }

                    // 多种克重，显示可折叠的克重卡片
                    return (
                      <div key={weight} className="bg-gray-50 rounded-xl overflow-hidden">
                        <div
                          onClick={() => onToggleGroup(weightKey)}
                          className="flex items-center justify-between p-3 cursor-pointer hover:bg-gray-100"
                        >
                          <div className="flex items-center gap-2">
                            <div className={`w-6 h-6 rounded flex items-center justify-center ${isWeightExpanded ? 'bg-amber-100' : 'bg-white'}`}>
                              {isWeightExpanded ? <ChevronUp size={14} className="text-amber-600" /> : <ChevronDown size={14} className="text-gray-500" />}
                            </div>
                            <span className="font-medium text-gray-800">{weight}g</span>
                            {products[0]?.warp_weight && products[0]?.weft_weight && (
                              <span className="text-xs text-gray-400 ml-1">经{products[0].warp_weight}+纬{products[0].weft_weight}</span>
                            )}
                            <span className="text-xs text-gray-500">({products.length}个颜色)</span>
                          </div>
                        </div>

                        {/* 克重展开内容 - 使用CSS Grid实现平滑高度动画 */}
                        <div
                          className="border-t border-gray-200 grid transition-all duration-300 ease-out"
                          style={{
                            gridTemplateRows: isWeightExpanded ? '1fr' : '0fr',
                            opacity: isWeightExpanded ? 1 : 0
                          }}
                        >
                          <div className="overflow-hidden">
                            <table className="w-full">
                              <thead className="bg-white/50 border-b border-gray-100">
                                <tr>
                                  <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">颜色</th>
                                  <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">产品码</th>
                                  <th className="px-3 py-2 text-left text-xs font-medium text-gray-500">库存</th>
                                  <th className="px-3 py-2 text-right text-xs font-medium text-gray-500">操作</th>
                                </tr>
                              </thead>
                              <tbody className="divide-y divide-gray-100">
                                {products.map(product => (
                                  <ProductRow
                                    key={product.id}
                                    product={product}
                                    ratios={productRatios[product.id]}
                                    onViewRecords={() => onViewRecords(product)}
                                    onViewPriceHistory={() => onViewPriceHistory(product)}
                                    onViewStockHistory={() => onViewStockHistory(product)}
                                    onEdit={() => onEdit(product)}
                                    onDelete={() => onDelete(product.id)}
                                  />
                                ))}
                              </tbody>
                            </table>
                          </div>
                        </div>
                      </div>
                    );
                  })}
                  </div>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    );
  }

  function ProductListMobile() {
    return (
      <div className="space-y-3">
        {Object.entries(productGroups).map(([productName, weightGroups]) => {
          const isNameExpanded = expandedGroups[productName];

          return (
            <div
              key={productName}
              className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden"
            >
              <div
                onClick={() => onToggleGroup(productName)}
                className="p-4 cursor-pointer hover:bg-gray-50"
              >
                <div className="flex justify-between items-start">
                  <div className="flex items-center gap-2 min-w-0">
                    <div className={`w-7 h-7 rounded-lg flex items-center justify-center flex-shrink-0 ${isNameExpanded ? 'bg-amber-100' : 'bg-gray-100'}`}>
                      {isNameExpanded ? <ChevronUp size={16} className="text-amber-600" /> : <ChevronDown size={16} className="text-gray-500" />}
                    </div>
                    <div className="min-w-0">
                      <p className="font-medium text-gray-900 text-sm truncate">{productName}</p>
                    </div>
                  </div>
                </div>
              </div>

              {/* 移动端展开内容 - 使用CSS Grid实现平滑高度动画 */}
              <div
                className="border-t border-gray-100 grid transition-all duration-300 ease-out"
                style={{
                  gridTemplateRows: isNameExpanded ? '1fr' : '0fr',
                  opacity: isNameExpanded ? 1 : 0
                }}
              >
                <div className="overflow-hidden bg-gray-50">
                  <div className="p-3 space-y-2">
                  {Object.entries(weightGroups).map(([weight, products]) => {
                    const hasNoWeight = weight === '__no_weight__';
                    const isSingleWeight = Object.keys(weightGroups).length === 1;

                    if (hasNoWeight) {
                      return (
                        <div key={weight} className="space-y-2">
                          {products.map(product => (
                            <ProductCardMobile
                              key={product.id}
                              product={product}
                              ratios={productRatios[product.id]}
                              onViewRecords={() => onViewRecords(product)}
                              onViewPriceHistory={() => onViewPriceHistory(product)}
                              onViewStockHistory={() => onViewStockHistory(product)}
                              onEdit={() => onEdit(product)}
                              onDelete={() => onDelete(product.id)}
                            />
                          ))}
                        </div>
                      );
                    }

                    if (isSingleWeight) {
                      return (
                        <div key={weight} className="bg-white rounded-lg border border-gray-200 overflow-hidden">
                          <div className="p-3 bg-gray-50 border-b border-gray-100">
                            <span className="font-medium text-gray-800 text-sm">{weight}g</span>
                            {products[0]?.warp_weight && products[0]?.weft_weight && (
                              <span className="text-xs text-gray-500 ml-1">经{products[0].warp_weight}+纬{products[0].weft_weight}</span>
                            )}
                          </div>
                          <div className="p-2 space-y-2">
                            {products.map(product => (
                              <ProductCardMobile
                                key={product.id}
                                product={product}
                                ratios={productRatios[product.id]}
                                onViewRecords={() => onViewRecords(product)}
                                onViewPriceHistory={() => onViewPriceHistory(product)}
                                onViewStockHistory={() => onViewStockHistory(product)}
                                onEdit={() => onEdit(product)}
                                onDelete={() => onDelete(product.id)}
                              />
                            ))}
                          </div>
                        </div>
                      );
                    }

                    return (
                      <div key={weight} className="bg-white rounded-lg border border-gray-200 overflow-hidden">
                        <div className="p-3">
                          <span className="font-medium text-gray-800 text-sm">{weight}g</span>
                          {products[0]?.warp_weight && products[0]?.weft_weight && (
                            <span className="text-xs text-gray-400 ml-1">经{products[0].warp_weight}+纬{products[0].weft_weight}</span>
                          )}
                        </div>
                        <div className="p-2 space-y-2">
                          {products.map(product => (
                            <ProductCardMobile
                              key={product.id}
                              product={product}
                              ratios={productRatios[product.id]}
                              onViewRecords={() => onViewRecords(product)}
                              onViewPriceHistory={() => onViewPriceHistory(product)}
                              onViewStockHistory={() => onViewStockHistory(product)}
                              onEdit={() => onEdit(product)}
                              onDelete={() => onDelete(product.id)}
                            />
                          ))}
                        </div>
                      </div>
                    );
                  })}
                  </div>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    );
  }
}

// 桌面端产品行
interface ProductRowProps {
  product: ProductWithInventory;
  ratios?: ProductYarnRatio[];
  onViewRecords: () => void;
  onViewPriceHistory: () => void;
  onViewStockHistory: () => void;
  onEdit: () => void;
  onDelete: () => void;
}

function ProductRow({ product, ratios, onViewRecords, onViewPriceHistory, onViewStockHistory, onEdit, onDelete }: ProductRowProps) {
  return (
    <tr className="bg-white hover:bg-gray-50/50">
      <td className="px-3 py-2">
        <div className="flex items-center gap-2">
          {product.image_url ? (
            <img
              src={product.image_url}
              alt={product.product_name}
              className="w-10 h-10 rounded-lg object-cover border border-gray-200 flex-shrink-0"
            />
          ) : (
            <div className="w-10 h-10 rounded-lg bg-gray-100 flex items-center justify-center flex-shrink-0">
              <ImageIcon className="w-5 h-5 text-gray-400" />
            </div>
          )}
          <div>
            <p className="font-medium text-gray-900 text-sm">{product.color}</p>
            <p className="text-xs text-gray-500">色号: {product.color_code}</p>
          </div>
        </div>
      </td>
      <td className="px-3 py-2">
        <span className="px-2 py-1 bg-gray-100 rounded-lg text-sm font-mono text-gray-700">
          {product.fabric_code}
        </span>
      </td>
      <td className="px-3 py-2">
        <div className="text-sm">
          <span className="text-gray-900 font-medium">{product.raw_fabric_rolls || 0}匹/件</span>
          <span className="text-gray-400 mx-1">·</span>
          <span className="text-gray-600">{product.raw_fabric_meters || 0}m</span>
        </div>
        {((product.in_records?.length || 0) > 0 || (product.out_records?.length || 0) > 0) && (
          <div className="text-xs text-gray-400 mt-1">
            <button
              onClick={(e) => { e.stopPropagation(); onViewRecords(); }}
              className="inline-flex items-center gap-1 px-2 py-0.5 bg-amber-50 text-amber-600 rounded text-xs font-medium hover:bg-amber-100"
            >
              <List className="w-3 h-3" />
              入库{product.in_records?.length || 0}条
              {(product.out_records?.length || 0) > 0 && ` · 出库${product.out_records?.length || 0}条`}
            </button>
          </div>
        )}
      </td>
      <td className="px-3 py-2 text-right">
        <button onClick={onViewStockHistory} className="text-purple-600 hover:text-purple-800 text-sm font-medium mr-2">出入库历史</button>
        <button onClick={onViewPriceHistory} className="text-emerald-600 hover:text-emerald-800 text-sm font-medium mr-2">价格历史</button>
        <button onClick={onEdit} className="text-amber-600 hover:text-amber-800 text-sm font-medium mr-2">编辑</button>
        <button onClick={onDelete} className="text-red-600 hover:text-red-800 text-sm font-medium">删除</button>
      </td>
    </tr>
  );
}

// 移动端产品卡片
interface ProductCardMobileProps {
  product: ProductWithInventory;
  ratios?: ProductYarnRatio[];
  onViewRecords: () => void;
  onViewPriceHistory: () => void;
  onViewStockHistory: () => void;
  onEdit: () => void;
  onDelete: () => void;
}

function ProductCardMobile({ product, ratios, onViewRecords, onViewPriceHistory, onViewStockHistory, onEdit, onDelete }: ProductCardMobileProps) {
  return (
    <div className="bg-white rounded-lg p-2.5 border border-gray-200">
      <div className="flex justify-between items-start mb-1.5">
        <div className="flex items-center gap-2">
          {product.image_url ? (
            <img
              src={product.image_url}
              alt={product.product_name}
              className="w-10 h-10 rounded-lg object-cover border border-gray-200 flex-shrink-0"
            />
          ) : (
            <div className="w-10 h-10 rounded-lg bg-gray-100 flex items-center justify-center flex-shrink-0">
              <ImageIcon className="w-5 h-5 text-gray-400" />
            </div>
          )}
          <div>
            <p className="font-medium text-gray-900 text-sm">{product.color}</p>
            <span className="px-1.5 py-0.5 bg-gray-100 rounded text-xs font-mono text-gray-600">
              {product.fabric_code}
            </span>
          </div>
        </div>
        <div className="text-right">
          <span className="text-sm font-medium text-gray-900">{product.raw_fabric_rolls || 0}匹/件</span>
          <span className="text-xs text-gray-500 ml-1">· {product.raw_fabric_meters || 0}米</span>
        </div>
      </div>
      {((product.in_records?.length || 0) > 0 || (product.out_records?.length || 0) > 0) && (
        <div className="text-xs text-gray-400 mb-1">
          <button
            onClick={(e) => { e.stopPropagation(); onViewRecords(); }}
            className="inline-flex items-center gap-1 px-2 py-0.5 bg-blue-50 text-blue-600 rounded text-xs font-medium hover:bg-blue-100"
          >
            <List className="w-3 h-3" />
            入库{product.in_records?.length || 0}条
            {(product.out_records?.length || 0) > 0 && ` · 出库${product.out_records?.length || 0}条`}
          </button>
        </div>
      )}
      <div className="flex gap-2">
        <button onClick={onViewStockHistory} className="flex-1 py-1.5 bg-purple-50 text-purple-600 rounded-lg text-xs font-medium hover:bg-purple-100">出入库历史</button>
        <button onClick={onViewPriceHistory} className="flex-1 py-1.5 bg-emerald-50 text-emerald-600 rounded-lg text-xs font-medium hover:bg-emerald-100">价格历史</button>
      </div>
      <div className="flex gap-2 mt-2">
        <button onClick={onEdit} className="flex-1 py-1.5 bg-blue-50 text-blue-600 rounded-lg text-xs font-medium hover:bg-blue-100">编辑</button>
        <button onClick={onDelete} className="flex-1 py-1.5 bg-red-50 text-red-600 rounded-lg text-xs font-medium hover:bg-red-100">删除</button>
      </div>
    </div>
  );
}
