import React, { useState, useCallback, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../../contexts/AuthContext';
import { purchaserApi, http } from '../../api';
import { useInventoryData } from '../../hooks/useInventoryData';
import { useResponsive } from '../../hooks/useResponsive';
import { useErrorHandler } from '../../hooks/useErrorHandler';
import { motion, AnimatePresence } from 'framer-motion';
import { Package, ArrowLeft, Plus, Search, List } from 'lucide-react';
import { WarehouseNav } from '../../components/warehouse/WarehouseNav';
import { ProductList } from '../../components/warehouse/ProductList';
import { InboundRecords } from '../../components/warehouse/InboundRecords';
import { ProductForm } from '../../components/warehouse/ProductForm';
import { InboundForm } from '../../components/warehouse/InboundForm';
import { OutboundForm } from '../../components/warehouse/OutboundForm';
import { InventoryRecordsModal } from '../../components/InventoryRecordsModal';
import { animationConfig } from '../../utils/constants';
import type { 
  ProductWithInventory, 
  ProductPriceHistory, 
  ProductInRecord,
  ProductYarnRatio 
} from '../../types';

type WarehouseTypeId = 'raw_fabric';
type SubMenuType = 'products' | 'inventory' | 'in_records' | 'out_records';

// 表单数据类型
interface ProductFormData {
  product_name: string;
  weight: string;
  warp_weight: string;
  weft_weight: string;
  total_weight: string;
  color: string;
  fabric_code: string;
  color_code: string;
  production_price: string;
  yarn_ratios: { yarn_name: string; ratio: number; yarn_type: 'warp' | 'weft' | 'all' }[];
  image_url?: string;
}

interface InboundFormData {
  product_id: string;
  batch_no: string;
  rolls: number;
  meters: number;
  notes: string;
}

interface OutboundFormData {
  product_id: string;
  batch_no: string;
  rolls: number;
  meters: number;
  notes: string;
  source_batch_id: string;
  recipient_company_id: string;
  recipient_company_name: string;
}

// 初始表单数据
const initialProductForm: ProductFormData = {
  product_name: '',
  weight: '',
  warp_weight: '',
  weft_weight: '',
  total_weight: '',
  color: '',
  fabric_code: '',
  color_code: '01',
  production_price: '',
  yarn_ratios: [{ yarn_name: '', ratio: 100, yarn_type: 'all' }]
};

const initialInboundForm: InboundFormData = {
  product_id: '',
  batch_no: '',
  rolls: 0,
  meters: 0,
  notes: ''
};

const initialOutboundForm: OutboundFormData = {
  product_id: '',
  batch_no: '',
  rolls: 0,
  meters: 0,
  notes: '',
  source_batch_id: '',
  recipient_company_id: '',
  recipient_company_name: ''
};

export function WarehouseManage() {
  const navigate = useNavigate();
  const { auth } = useAuth();
  const { isMobile } = useResponsive();
  const handleError = useErrorHandler();

  // 菜单状态
  const [activeSubMenu, setActiveSubMenu] = useState<SubMenuType>('products');

  // 搜索
  const [searchQuery, setSearchQuery] = useState('');

  // 展开状态
  const [expandedGroups, setExpandedGroups] = useState<Record<string, boolean>>({});

  // 模态框状态
  const [showProductModal, setShowProductModal] = useState(false);
  const [showInModal, setShowInModal] = useState(false);
  const [showOutModal, setShowOutModal] = useState(false);
  const [editingProduct, setEditingProduct] = useState<ProductWithInventory | null>(null);

  // 表单状态
  const [productForm, setProductForm] = useState<ProductFormData>(initialProductForm);
  const [inForm, setInForm] = useState<InboundFormData>(initialInboundForm);
  const [outForm, setOutForm] = useState<OutboundFormData>(initialOutboundForm);

  // 记录弹窗状态
  const [recordsModalOpen, setRecordsModalOpen] = useState(false);
  const [selectedRecords, setSelectedRecords] = useState<ProductInRecord[]>([]);
  const [selectedProductName, setSelectedProductName] = useState('');

  // 价格历史弹窗
  const [priceHistoryModalOpen, setPriceHistoryModalOpen] = useState(false);
  const [selectedPriceHistory, setSelectedPriceHistory] = useState<ProductPriceHistory[]>([]);

  // 出入库历史弹窗
  const [stockHistoryModalOpen, setStockHistoryModalOpen] = useState(false);
  const [selectedStockHistory, setSelectedStockHistory] = useState<ProductInRecord[]>([]);

  // 使用优化的数据获取 Hook
  const { products, productRatios, batches, loading, refetch } = useInventoryData({
    companyId: auth.company?.id || null,
    activeType: 'raw_fabric'
  });


  // 切换分组展开
  const toggleGroup = useCallback((key: string) => {
    setExpandedGroups(prev => ({ ...prev, [key]: !prev[key] }));
  }, []);

  // 筛选产品
  const filteredProducts = useMemo(() => {
    if (!searchQuery) return products;
    return products.filter(p =>
      p.product_name.includes(searchQuery) ||
      p.fabric_code.includes(searchQuery) ||
      p.color.includes(searchQuery)
    );
  }, [products, searchQuery]);

  // 保存产品
  const handleSaveProduct = useCallback(async (formData: ProductFormData) => {
    if (!auth.company) return;

    const productData = {
      product_name: formData.product_name,
      weight: parseFloat(formData.total_weight) || parseFloat(formData.weight) || 0,
      warp_weight: parseFloat(formData.warp_weight) || null,
      weft_weight: parseFloat(formData.weft_weight) || null,
      total_weight: parseFloat(formData.total_weight) || null,
      color: formData.color,
      fabric_code: formData.fabric_code.toUpperCase(),
      color_code: formData.color_code,
      production_price: parseFloat(formData.production_price) || 0,
      image_url: formData.image_url || null
    };

    const yarnRatios = formData.yarn_ratios.filter(r => r.yarn_name && r.ratio > 0);

    try {
      if (editingProduct) {
        await http.put(`/purchaser/products/${editingProduct.id}`, {
          ...productData,
          yarn_ratios: yarnRatios
        });
      } else {
        await http.post('/purchaser/products', {
          ...productData,
          yarn_ratios: yarnRatios
        });
      }

      setShowProductModal(false);
      setEditingProduct(null);
      setProductForm(initialProductForm);
      await refetch();
    } catch (err) {
      handleError(err, { userMessage: editingProduct ? '更新失败' : '创建失败' });
    }
  }, [auth.company, auth.user, editingProduct, refetch]);

  // 删除产品
  const handleDeleteProduct = useCallback(async (id: string) => {
    if (!confirm('确定要删除这个产品吗？')) return;

    try {
      await purchaserApi.deleteProduct(id);
      await refetch();
    } catch (err) {
      handleError(err, { userMessage: '删除失败' });
    }
  }, [refetch]);

  // 编辑产品
  const handleEditProduct = useCallback((product: ProductWithInventory) => {
    setEditingProduct(product);
    setProductForm({
      product_name: product.product_name,
      weight: String(product.weight),
      warp_weight: String(product.warp_weight || ''),
      weft_weight: String(product.weft_weight || ''),
      total_weight: String(product.total_weight || product.weight || ''),
      color: product.color,
      fabric_code: product.fabric_code,
      color_code: product.color_code,
      production_price: String(product.production_price || ''),
      yarn_ratios: productRatios[product.id]?.length
        ? productRatios[product.id].map(r => ({ yarn_name: r.yarn_name, ratio: r.ratio, yarn_type: (r.yarn_type as 'warp' | 'weft' | 'all') || 'all' }))
        : [{ yarn_name: '', ratio: 0, yarn_type: 'all' }],
      image_url: product.image_url || undefined
    });
    setShowProductModal(true);
  }, [productRatios]);

  // 查看入库记录（生产记录）- 合并入库和出库记录
  const handleViewRecords = useCallback((product: ProductWithInventory) => {
    // 合并入库和出库记录，并添加类型标记
    const inRecords = (product.in_records || []).map(r => ({ ...r, record_type: 'in' as const }));
    const outRecords = (product.out_records || []).map(r => ({ ...r, record_type: 'out' as const }));
    const allRecords = [...inRecords, ...outRecords].sort((a, b) => {
      const dateA = new Date(a.created_at || 0).getTime();
      const dateB = new Date(b.created_at || 0).getTime();
      return dateB - dateA; // 降序，最新的在前
    });
    setSelectedRecords(allRecords);
    setSelectedProductName(`${product.product_name}-${product.weight}g-${product.color}`);
    setRecordsModalOpen(true);
  }, []);

  // 查看价格历史
  const handleViewPriceHistory = useCallback(async (product: ProductWithInventory) => {
    try {
      const data = await purchaserApi.priceHistory(product.id);
      setSelectedPriceHistory(data || []);
      setSelectedProductName(`${product.product_name}-${product.weight}g-${product.color}`);
      setPriceHistoryModalOpen(true);
    } catch {
      setSelectedPriceHistory([]);
      setSelectedProductName(`${product.product_name}-${product.weight}g-${product.color}`);
      setPriceHistoryModalOpen(true);
    }
  }, []);

  // 查看出入库历史 - 合并入库和出库记录
  const handleViewStockHistory = useCallback((product: ProductWithInventory) => {
    // 合并入库和出库记录，并添加类型标记
    const inRecords = (product.in_records || []).map(r => ({ ...r, record_type: 'in' as const }));
    const outRecords = (product.out_records || []).map(r => ({ ...r, record_type: 'out' as const }));
    const allRecords = [...inRecords, ...outRecords].sort((a, b) => {
      const dateA = new Date(a.created_at || 0).getTime();
      const dateB = new Date(b.created_at || 0).getTime();
      return dateB - dateA; // 降序，最新的在前
    });
    setSelectedStockHistory(allRecords);
    setSelectedProductName(`${product.product_name}-${product.weight}g-${product.color}`);
    setStockHistoryModalOpen(true);
  }, []);

  // 提交入库
  const handleInSubmit = useCallback(async () => {
    if (!auth.company || !inForm.product_id || !inForm.batch_no) return;

    try {
      await purchaserApi.inbound(inForm.product_id, {
        batch_no: inForm.batch_no,
        rolls: inForm.rolls,
        meters: inForm.meters,
        notes: inForm.notes || undefined
      });

      setShowInModal(false);
      setInForm(initialInboundForm);
      await refetch();
    } catch (err) {
      handleError(err, { userMessage: '入库失败' });
    }
  }, [auth.company, auth.user, inForm, products, refetch]);

  // 提交出库
  const handleOutSubmit = useCallback(async () => {
    if (!auth.company || !outForm.product_id || !outForm.batch_no || !outForm.source_batch_id || !outForm.recipient_company_id) return;

    const product = products.find(p => p.id === outForm.product_id);
    if (!product) {
      handleError(new Error('产品不存在'), { userMessage: '产品不存在' });
      return;
    }
    if ((product.total_stock || 0) < outForm.meters) {
      handleError(new Error('库存不足'), { userMessage: `库存不足，当前库存: ${product.total_stock}米` });
      return;
    }
    if ((product.raw_fabric_rolls || 0) < outForm.rolls) {
      handleError(new Error('库存不足'), { userMessage: `库存匹/件数不足，当前库存: ${product.raw_fabric_rolls}匹/件` });
      return;
    }

    try {
      await purchaserApi.outbound(outForm.product_id, {
        batch_no: outForm.batch_no,
        rolls: outForm.rolls,
        meters: outForm.meters,
        outbound_type: 'manual',
        notes: outForm.notes || undefined,
        recipient_company_id: outForm.recipient_company_id
      });

      setShowOutModal(false);
      setOutForm(initialOutboundForm);
      await refetch();
    } catch (err) {
      handleError(err, { userMessage: '出库失败' });
    }
  }, [auth.company, auth.user, outForm, products, refetch]);

  // 打开新建产品模态框
  const openNewProductModal = useCallback(() => {
    setEditingProduct(null);
    setProductForm(initialProductForm);
    setShowProductModal(true);
  }, []);

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <header className="bg-white border-b border-gray-200 sticky top-0 z-10">
        <div className="max-w-7xl mx-auto px-3 sm:px-4 py-3 sm:py-4 flex items-center gap-3 sm:gap-4">
          <button
            onClick={() => navigate('/purchaser')}
            className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
          >
            <ArrowLeft className="w-5 h-5 text-gray-600" />
          </button>
          <h1 className="text-base sm:text-lg font-bold text-gray-900">产品信息</h1>
        </div>
      </header>

      <div className={`max-w-7xl mx-auto py-4 sm:py-6 ${isMobile ? 'px-0' : 'px-4'}`}>
        {/* 导航菜单 */}
        <div className={`${isMobile ? 'px-3 sm:px-4' : ''}`}>
          <WarehouseNav
            activeSubMenu={activeSubMenu}
            onSubMenuChange={(menu) => setActiveSubMenu(menu as SubMenuType)}
          />
        </div>

        {/* 内容区域 */}
        <div className={`${isMobile ? 'px-3 sm:px-4' : ''}`}>
          {loading ? (
            <div className="flex items-center justify-center py-16 sm:py-20">
              <div className="flex flex-col items-center gap-2 sm:gap-3">
                <div className="w-7 h-7 sm:w-8 sm:h-8 border-2 border-blue-500 border-t-transparent rounded-full animate-spin" />
                <p className="text-gray-500 text-xs sm:text-sm">加载中...</p>
              </div>
            </div>
          ) : (
            <div>
              {/* 产品管理 */}
              {activeSubMenu === 'products' && (
                <div>
                  {/* 搜索和新建 */}
                  <div className={`flex ${isMobile ? 'flex-col gap-3' : 'justify-between items-center'} mb-3 sm:mb-4`}>
                    <div className={`relative ${isMobile ? 'w-full' : ''}`}>
                      <Search className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
                      <input
                        type="text"
                        placeholder="搜索产品名称、产品码、颜色..."
                        value={searchQuery}
                        onChange={e => setSearchQuery(e.target.value)}
                        className={`pl-9 sm:pl-10 pr-4 py-2 sm:py-2.5 border border-gray-200 rounded-xl text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all ${isMobile ? 'w-full' : 'w-80'}`}
                      />
                    </div>
                    <button
                      onClick={openNewProductModal}
                      className={`flex items-center justify-center gap-1.5 sm:gap-2 px-3 sm:px-4 py-2 sm:py-2.5 bg-gradient-to-r from-blue-500 to-indigo-500 text-white rounded-xl text-xs sm:text-sm font-medium hover:from-blue-600 hover:to-indigo-600 transition-all shadow-md hover:shadow-lg ${isMobile ? 'w-full' : ''}`}
                    >
                      <Plus className="w-3.5 h-3.5 sm:w-4 sm:h-4" />
                      新建产品
                    </button>
                  </div>

                  {/* 产品列表 */}
                  {filteredProducts.length === 0 ? (
                    <div className="text-center py-10 sm:py-12 bg-white rounded-2xl border border-dashed border-gray-300">
                      <Package className="w-10 h-10 sm:w-12 sm:h-12 text-gray-300 mx-auto mb-3" />
                      <p className="text-gray-500 mb-4 text-sm sm:text-base">暂无产品</p>
                      <button
                        onClick={openNewProductModal}
                        className="flex items-center gap-2 px-5 sm:px-6 py-2.5 sm:py-3 bg-gradient-to-r from-blue-500 to-indigo-500 text-white rounded-xl text-sm font-medium hover:from-blue-600 hover:to-indigo-600 transition-all shadow-md mx-auto"
                      >
                        <Plus className="w-4 h-4" />
                        创建产品
                      </button>
                    </div>
                  ) : (
                    <ProductList
                      products={filteredProducts}
                      productRatios={productRatios}
                      expandedGroups={expandedGroups}
                      onToggleGroup={toggleGroup}
                      onViewRecords={handleViewRecords}
                      onViewPriceHistory={handleViewPriceHistory}
                      onViewStockHistory={handleViewStockHistory}
                      onEdit={handleEditProduct}
                      onDelete={handleDeleteProduct}
                    />
                  )}
                </div>
              )}

              {/* 入库记录 */}
              {activeSubMenu === 'in_records' && (
                <div>
                  <div className={`flex ${isMobile ? 'flex-col gap-3' : 'justify-between items-center'} mb-3 sm:mb-4`}>
                    <h3 className="font-semibold text-gray-900 text-sm sm:text-base">生产记录</h3>
                    <button
                      onClick={() => setShowInModal(true)}
                      className={`flex items-center justify-center gap-1.5 sm:gap-2 px-3 sm:px-4 py-2 sm:py-2.5 bg-gradient-to-r from-emerald-500 to-green-500 text-white rounded-xl text-xs sm:text-sm font-medium hover:from-emerald-600 hover:to-green-600 transition-all shadow-md hover:shadow-lg ${isMobile ? 'w-full' : ''}`}
                    >
                      <Plus className="w-3.5 h-3.5 sm:w-4 sm:h-4" />
                      原坯布生产
                    </button>
                  </div>

                  {batches.length === 0 ? (
                    <div className="text-center py-10 sm:py-12 bg-white rounded-2xl border border-dashed border-gray-300">
                      <Package className="w-10 h-10 sm:w-12 sm:h-12 text-gray-300 mx-auto mb-3" />
                      <p className="text-gray-500 text-sm sm:text-base">暂无生产记录</p>
                    </div>
                  ) : (
                    <InboundRecords batches={batches} />
                  )}
                </div>
              )}

              {/* 出库记录 */}
              {activeSubMenu === 'out_records' && (
                <div>
                  <div className={`flex ${isMobile ? 'flex-col gap-3' : 'justify-between items-center'} mb-3 sm:mb-4`}>
                    <h3 className="font-semibold text-gray-900 text-sm sm:text-base">出库记录</h3>
                    <button
                      onClick={() => setShowOutModal(true)}
                      className={`flex items-center justify-center gap-1.5 sm:gap-2 px-3 sm:px-4 py-2 sm:py-2.5 bg-gradient-to-r from-amber-500 to-orange-500 text-white rounded-xl text-xs sm:text-sm font-medium hover:from-amber-600 hover:to-orange-600 transition-all shadow-md hover:shadow-lg ${isMobile ? 'w-full' : ''}`}
                    >
                      <Plus className="w-3.5 h-3.5 sm:w-4 sm:h-4" />
                      手动出库
                    </button>
                  </div>

                  <div className="text-center py-10 sm:py-12 bg-white rounded-2xl border border-dashed border-gray-300">
                    <Package className="w-10 h-10 sm:w-12 sm:h-12 text-gray-300 mx-auto mb-3" />
                    <p className="text-gray-500 text-sm sm:text-base">暂无出库记录</p>
                    <p className="text-gray-400 text-xs mt-1">可通过"手动出库"按钮或创建水洗计划自动出库</p>
                  </div>
                </div>
              )}

              {/* 库存管理 */}
              {activeSubMenu === 'inventory' && (
                <div className="text-center py-12 sm:py-16 bg-white rounded-2xl border border-dashed border-gray-300">
                  <div className="w-14 h-14 sm:w-16 sm:h-16 bg-gray-100 rounded-2xl flex items-center justify-center mx-auto mb-4">
                    <Package className="w-7 h-7 sm:w-8 sm:h-8 text-gray-400" />
                  </div>
                  <p className="text-gray-500 text-base sm:text-lg font-medium mb-2">库存管理</p>
                  <p className="text-gray-400 text-sm">功能开发中，敬请期待</p>
                </div>
              )}
            </div>
          )}
        </div>
      </div>

      {/* 产品表单模态框 */}
      <AnimatePresence>
        {showProductModal && (
          <ProductForm
            isOpen={showProductModal}
            onClose={() => {
              setShowProductModal(false);
              setEditingProduct(null);
            }}
            onSave={handleSaveProduct}
            editingProduct={editingProduct}
            initialFormData={productForm}
            productRatios={productRatios}
            companyId={auth.company?.id}
          />
        )}
      </AnimatePresence>

      {/* 入库表单模态框 */}
      <AnimatePresence>
        {showInModal && (
          <InboundForm
            isOpen={showInModal}
            onClose={() => {
              setShowInModal(false);
              setInForm(initialInboundForm);
            }}
            onSubmit={handleInSubmit}
            products={products}
            formData={inForm}
            setFormData={setInForm}
          />
        )}
      </AnimatePresence>

      {/* 出库表单模态框 */}
      <AnimatePresence>
        {showOutModal && (
          <OutboundForm
            isOpen={showOutModal}
            onClose={() => {
              setShowOutModal(false);
              setOutForm(initialOutboundForm);
            }}
            onSubmit={handleOutSubmit}
            products={products}
            formData={outForm}
            setFormData={setOutForm}
          />
        )}
      </AnimatePresence>

      {/* 入库记录弹窗 */}
      <InventoryRecordsModal
        isOpen={recordsModalOpen}
        onClose={() => setRecordsModalOpen(false)}
        records={selectedRecords}
        title={`${selectedProductName} - 生产记录`}
      />

      {/* 价格历史弹窗 */}
      <AnimatePresence>
        {priceHistoryModalOpen && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4"
            onClick={() => setPriceHistoryModalOpen(false)}
          >
            <motion.div
              initial={{ scale: 0.95, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.95, opacity: 0 }}
              className="bg-white rounded-2xl shadow-xl w-full max-w-2xl max-h-[80vh] overflow-hidden"
              onClick={e => e.stopPropagation()}
            >
              {/* 弹窗头部 */}
              <div className="flex items-center justify-between p-4 border-b border-gray-200">
                <h3 className="text-lg font-semibold text-gray-900">{selectedProductName} - 采购价变动记录</h3>
                <button
                  onClick={() => setPriceHistoryModalOpen(false)}
                  className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
                >
                  <svg className="w-5 h-5 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                  </svg>
                </button>
              </div>

              {/* 弹窗内容 */}
              <div className="p-4 max-h-[60vh] overflow-y-auto">
                {selectedPriceHistory.length === 0 ? (
                  <div className="text-center py-8">
                    <p className="text-gray-500">暂无价格变动记录</p>
                  </div>
                ) : (
                  <div className="space-y-3">
                    {selectedPriceHistory.map((record, index) => (
                      <div key={record.id} className="bg-gray-50 rounded-xl p-4">
                        <div className="flex items-center justify-between mb-2">
                          <span className="text-sm text-gray-500">#{selectedPriceHistory.length - index}</span>
                          <span className="text-xs text-gray-400">{new Date(record.created_at).toLocaleString('zh-CN')}</span>
                        </div>
                        <div className="grid grid-cols-3 gap-4">
                          <div>
                            <p className="text-xs text-gray-500 mb-1">原价格</p>
                            <p className="text-sm font-medium text-gray-700">¥{record.old_price.toFixed(2)}</p>
                          </div>
                          <div>
                            <p className="text-xs text-gray-500 mb-1">新价格</p>
                            <p className="text-sm font-medium text-emerald-600">¥{record.new_price.toFixed(2)}</p>
                          </div>
                          <div>
                            <p className="text-xs text-gray-500 mb-1">变动金额</p>
                            <p className={`text-sm font-medium ${record.change_amount >= 0 ? 'text-red-500' : 'text-green-500'}`}>
                              {record.change_amount >= 0 ? '+' : ''}¥{record.change_amount.toFixed(2)}
                            </p>
                          </div>
                        </div>
                        <div className="mt-2 pt-2 border-t border-gray-200">
                          <p className="text-xs text-gray-500">
                            操作人: {record.operator_name || '未知'} · 原因: {record.change_reason || '-'}
                          </p>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* 出入库历史弹窗 */}
      <AnimatePresence>
        {stockHistoryModalOpen && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4"
            onClick={() => setStockHistoryModalOpen(false)}
          >
            <motion.div
              initial={{ scale: 0.95, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.95, opacity: 0 }}
              className="bg-white rounded-2xl shadow-xl w-full max-w-2xl max-h-[80vh] overflow-hidden"
              onClick={e => e.stopPropagation()}
            >
              {/* 弹窗头部 */}
              <div className="flex items-center justify-between p-4 border-b border-gray-200">
                <h3 className="text-lg font-semibold text-gray-900">{selectedProductName} - 出入库历史</h3>
                <button
                  onClick={() => setStockHistoryModalOpen(false)}
                  className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
                >
                  <svg className="w-5 h-5 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                  </svg>
                </button>
              </div>

              {/* 弹窗内容 */}
              <div className="p-4 max-h-[60vh] overflow-y-auto">
                {selectedStockHistory.length === 0 ? (
                  <div className="text-center py-8">
                    <p className="text-gray-500">暂无出入库记录</p>
                  </div>
                ) : (
                  <div className="space-y-3">
                    {selectedStockHistory.map((record, index) => (
                      <div key={record.id} className={`rounded-xl p-4 ${record.record_type === 'out' ? 'bg-red-50' : 'bg-gray-50'}`}>
                        <div className="flex items-center justify-between mb-2">
                          <div className="flex items-center gap-2">
                            <span className="text-sm text-gray-500">#{selectedStockHistory.length - index}</span>
                            {record.record_type === 'out' ? (
                              <span className="text-xs px-2 py-0.5 bg-red-100 text-red-600 rounded">出库</span>
                            ) : (
                              <span className="text-xs px-2 py-0.5 bg-emerald-100 text-emerald-600 rounded">入库</span>
                            )}
                          </div>
                          <span className="text-xs text-gray-400">{new Date(record.created_at).toLocaleString('zh-CN')}</span>
                        </div>
                        <div className="grid grid-cols-3 gap-4">
                          <div>
                            <p className="text-xs text-gray-500 mb-1">批号</p>
                            <p className="text-sm font-medium text-gray-700">{record.batch_no || '-'}</p>
                          </div>
                          <div>
                            <p className="text-xs text-gray-500 mb-1">匹/件数</p>
                            <p className={`text-sm font-medium ${record.record_type === 'out' ? 'text-red-600' : 'text-blue-600'}`}>
                              {record.record_type === 'out' ? '-' : ''}{record.rolls}匹/件
                            </p>
                          </div>
                          <div>
                            <p className="text-xs text-gray-500 mb-1">米数</p>
                            <p className={`text-sm font-medium ${record.record_type === 'out' ? 'text-red-600' : 'text-emerald-600'}`}>
                              {record.record_type === 'out' ? '-' : ''}{record.meters}米
                            </p>
                          </div>
                        </div>
                        {/* 出库记录显示生产批号和接手公司 */}
                        {record.record_type === 'out' && (
                          <div className="mt-2 pt-2 border-t border-red-200">
                            <div className="grid grid-cols-2 gap-4">
                              <div>
                                <p className="text-xs text-gray-500 mb-1">来源生产批号</p>
                                <p className="text-sm font-medium text-amber-700">{record.source_batch_id ? '已关联' : '未关联'}</p>
                              </div>
                              <div>
                                <p className="text-xs text-gray-500 mb-1">接手公司</p>
                                <p className="text-sm font-medium text-blue-700">{record.recipient_company_name || '-'}</p>
                              </div>
                            </div>
                          </div>
                        )}
                        {/* 入库记录显示来源 */}
                        {record.record_type === 'in' && record.source && (
                          <div className="mt-2 pt-2 border-t border-gray-200">
                            <p className="text-xs text-gray-500">
                              来源: {record.source === 'textile' ? `纺织厂${record.factory_name ? `(${record.factory_name})` : ''}` : '自录入'}
                            </p>
                          </div>
                        )}
                        {record.notes && (
                          <div className="mt-2 pt-2 border-t border-gray-200">
                            <p className="text-xs text-gray-500">备注: {record.notes}</p>
                          </div>
                        )}
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
