import React, { useState, useRef, useCallback, useEffect } from 'react';
import { motion } from 'framer-motion';
import { X, Package, Tag, Hash, Palette, DollarSign, Layers, Plus, Minus, Image as ImageIcon, Upload, Trash2, Search } from 'lucide-react';
import { useResponsive } from '../../hooks/useResponsive';
import { http } from '../../api';
import type { Product, ProductYarnRatio } from '../../types';

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 ProductFormProps {
  isOpen: boolean;
  onClose: () => void;
  onSave: (formData: ProductFormData) => void;
  editingProduct: Product | null;
  initialFormData?: ProductFormData;
  productRatios: Record<string, ProductYarnRatio[]>;
  companyId?: string;
}

// 产品搜索建议项
interface ProductSuggestion {
  id: string;
  product_name: string;
  total_weight: number;
  warp_weight: number | null;
  weft_weight: number | null;
  color: string;
  fabric_code: string;
  color_code: string;
  production_price: number;
  image_url: string | null;
}

// 纱线类型选项
const yarnTypeOptions = [
  { value: 'warp', label: '经线' },
  { value: 'weft', label: '纬线' },
  { value: 'all', label: '全部' }
];

// 默认初始表单数据
const defaultInitialForm: 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' }],
  image_url: undefined
};

export function ProductForm({
  isOpen,
  onClose,
  onSave,
  editingProduct,
  initialFormData,
  productRatios,
  companyId
}: ProductFormProps) {
  const { isMobile } = useResponsive();
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [uploading, setUploading] = useState(false);

  // 表单状态移到组件内部，避免父组件重新渲染
  const [formData, setFormData] = useState<ProductFormData>(() => {
    if (initialFormData) return { ...initialFormData };
    return { ...defaultInitialForm };
  });

  const [previewUrl, setPreviewUrl] = useState<string | null>(formData.image_url || null);

  // 当编辑产品变化时，加载产品数据
  useEffect(() => {
    if (editingProduct) {
      const ratios = productRatios[editingProduct.id] || [];
      setFormData({
        product_name: editingProduct.product_name || '',
        weight: String(editingProduct.weight || ''),
        warp_weight: String(editingProduct.warp_weight || ''),
        weft_weight: String(editingProduct.weft_weight || ''),
        total_weight: String(editingProduct.total_weight || ''),
        color: editingProduct.color || '',
        fabric_code: editingProduct.fabric_code || '',
        color_code: editingProduct.color_code || '01',
        production_price: String(editingProduct.production_price || ''),
        yarn_ratios: ratios.length > 0
          ? ratios.map(r => ({ yarn_name: r.yarn_name, ratio: r.ratio, yarn_type: (r.yarn_type as 'warp' | 'weft' | 'all') || 'all' }))
          : [{ yarn_name: '', ratio: 100, yarn_type: 'all' }],
        image_url: editingProduct.image_url || undefined
      });
      setPreviewUrl(editingProduct.image_url || null);
    } else if (initialFormData) {
      setFormData({ ...initialFormData });
      setPreviewUrl(initialFormData.image_url || null);
    } else {
      setFormData({ ...defaultInitialForm });
      setPreviewUrl(null);
    }
    // 清除搜索建议
    setProductSuggestions([]);
    setShowProductSuggestions(false);
    setWeightSuggestions([]);
    setShowWeightSuggestions(false);
  }, [editingProduct, initialFormData, productRatios, isOpen]);

  // 产品搜索相关状态
  const [productSuggestions, setProductSuggestions] = useState<ProductSuggestion[]>([]);
  const [showProductSuggestions, setShowProductSuggestions] = useState(false);
  const [isSearching, setIsSearching] = useState(false);
  const [weightSuggestions, setWeightSuggestions] = useState<number[]>([]);
  const [showWeightSuggestions, setShowWeightSuggestions] = useState(false);
  const searchTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  // 搜索产品（按名称）
  const searchProducts = useCallback(async (query: string) => {
    if (!companyId || query.length < 1) {
      setProductSuggestions([]);
      setShowProductSuggestions(false);
      return;
    }

    setIsSearching(true);
    setShowProductSuggestions(true);
    try {
      const res = await http.get<ProductSuggestion[]>('/purchaser/products', {
        search: query,
        page_size: 10,
      });

      setProductSuggestions(res.data || []);
    } catch {
      setProductSuggestions([]);
    } finally {
      setIsSearching(false);
    }
  }, [companyId]);

  // 搜索克重（按产品名称）
  const searchWeights = useCallback(async (productName: string) => {
    if (!companyId || !productName) {
      setWeightSuggestions([]);
      return;
    }

    try {
      const res = await http.get<{ total_weight: number | null }[]>('/purchaser/products', {
        search: productName,
        page_size: 20,
      });

      const weights = (res.data || [])
        .map(p => p.total_weight)
        .filter((w): w is number => w !== null && w > 0);
      const uniqueWeights = Array.from(new Set(weights));
      setWeightSuggestions(uniqueWeights.sort((a, b) => a - b));
    } catch {
      setWeightSuggestions([]);
    }
  }, [companyId]);

  // 处理成品名称输入
  const handleProductNameChange = (value: string) => {
    // 只更新表单数据，不触发搜索
    setFormData(prev => ({ ...prev, product_name: value }));

    // 清除之前的搜索定时器
    if (searchTimeoutRef.current) {
      clearTimeout(searchTimeoutRef.current);
    }

    // 延迟搜索，避免频繁请求和输入时的界面跳动
    if (value.length >= 1) {
      searchTimeoutRef.current = setTimeout(() => {
        searchProducts(value);
        setShowProductSuggestions(true);
      }, 300);
    } else {
      setShowProductSuggestions(false);
      setProductSuggestions([]);
    }
  };

  // 从数据库查询已存在的最大产品码数字，生成下一个
  const generateNextFabricCode = async (companyId: string, prefix: string): Promise<string> => {
    if (!prefix) return '';

    try {
      const res = await http.get<{ fabric_code: string }[]>('/purchaser/products', {
        search: prefix,
        page_size: 100,
      });
      const data = res.data || [];

      if (data.length === 0) {
        return `${prefix}1`;
      }

      let maxNum = 0;
      data.forEach(item => {
        const code = item.fabric_code;
        const match = code.match(/^(.*?)(\d+)$/);
        if (match && match[1].toUpperCase() === prefix.toUpperCase()) {
          const num = parseInt(match[2], 10);
          if (num > maxNum) {
            maxNum = num;
          }
        }
      });

      return `${prefix}${maxNum + 1}`;
    } catch {
      return `${prefix}1`;
    }
  };

  // 从数据库查询已存在的最大色号数字，生成下一个
  const generateNextColorCode = async (
    companyId: string,
    productName: string,
    totalWeight: number | null
  ): Promise<string> => {
    try {
      const res = await http.get<{ color_code: string }[]>('/purchaser/products', {
        search: productName,
        page_size: 100,
      });
      const data = res.data || [];

      if (data.length === 0) {
        return '01';
      }

      let maxNum = 0;
      data.forEach(item => {
        const code = item.color_code;
        const num = parseInt(code, 10);
        if (!isNaN(num) && num > maxNum) {
          maxNum = num;
        }
      });

      const nextNum = maxNum + 1;
      return nextNum < 10 ? `0${nextNum}` : String(nextNum);
    } catch {
      return '01';
    }
  };

  // 选择产品建议
  const selectProductSuggestion = async (suggestion: ProductSuggestion) => {
    // 获取该产品的纱线配比
    const ratios = productRatios[suggestion.id] || [];

    // 提取产品码前缀并生成新的产品码
    let newFabricCode = '';
    const fabricMatch = suggestion.fabric_code.match(/^(.*?)(\d+)$/);
    if (fabricMatch && companyId) {
      const prefix = fabricMatch[1];
      newFabricCode = await generateNextFabricCode(companyId, prefix);
    } else {
      newFabricCode = suggestion.fabric_code;
    }

    // 生成色号（基于该产品名称-克重组合的最大值+1，色号在产品名称-克重下连续递增）
    let newColorCode = '01';
    if (companyId) {
      newColorCode = await generateNextColorCode(
        companyId,
        suggestion.product_name,
        suggestion.total_weight
      );
    }

    setFormData(prev => ({
      ...prev,
      product_name: suggestion.product_name,
      // 自动填写克重
      total_weight: suggestion.total_weight ? String(suggestion.total_weight) : '',
      warp_weight: suggestion.warp_weight ? String(suggestion.warp_weight) : '',
      weft_weight: suggestion.weft_weight ? String(suggestion.weft_weight) : '',
      // 颜色需要用户自己输入，不自动填写
      color: '',
      // 产品码自动生成（基于数据库最大值+1）
      fabric_code: newFabricCode,
      // 色号自动生成（基于该产品名称-克重-颜色组合的最大值+1）
      color_code: newColorCode,
      // 自动填写生产采购价
      production_price: suggestion.production_price ? String(suggestion.production_price) : '',
      // 自动填写纱线配比
      yarn_ratios: ratios.length > 0
        ? ratios.map(r => ({ yarn_name: r.yarn_name, ratio: r.ratio, yarn_type: (r.yarn_type as 'warp' | 'weft' | 'all') || 'all' }))
        : [{ yarn_name: '', ratio: 100, yarn_type: 'all' }],
      image_url: suggestion.image_url || undefined
    }));

    if (suggestion.image_url) {
      setPreviewUrl(suggestion.image_url);
    }

    setShowProductSuggestions(false);

    // 加载该产品的克重建议
    searchWeights(suggestion.product_name);
  };

  // 处理总克重输入
  const handleTotalWeightChange = (value: string) => {
    setFormData(prev => ({ ...prev, total_weight: value }));

    // 克重输入时不触发搜索建议，避免界面跳动
    // 只在聚焦时显示建议
  };

  // 选择克重建议
  const selectWeightSuggestion = (weight: number) => {
    setFormData(prev => ({ ...prev, total_weight: String(weight) }));
    setShowWeightSuggestions(false);
  };

  // 点击外部关闭建议列表
  useEffect(() => {
    const handleClickOutside = (e: MouseEvent) => {
      const target = e.target as HTMLElement;
      if (!target.closest('.product-search-container')) {
        setShowProductSuggestions(false);
      }
      if (!target.closest('.weight-search-container')) {
        setShowWeightSuggestions(false);
      }
    };

    document.addEventListener('click', handleClickOutside);
    return () => document.removeEventListener('click', handleClickOutside);
  }, []);

  // 清理定时器
  useEffect(() => {
    return () => {
      if (searchTimeoutRef.current) {
        clearTimeout(searchTimeoutRef.current);
      }
    };
  }, []);

  // 处理图片选择
  const handleImageSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    // 验证文件类型
    if (!file.type.startsWith('image/')) {
      alert('请选择图片文件');
      return;
    }

    // 验证文件大小（最大 5MB）
    if (file.size > 5 * 1024 * 1024) {
      alert('图片大小不能超过 5MB');
      return;
    }

    setUploading(true);

    try {
      // TODO: 文件上传接口待后端实现
      const formDataObj = new FormData();
      formDataObj.append('file', file);
      formDataObj.append('bucket', 'product_images');
      formDataObj.append('path_prefix', 'products');

      const res = await fetch('/api/v1/common/upload', {
        method: 'POST',
        body: formDataObj,
      });

      if (!res.ok) {
        alert('图片上传失败');
        setUploading(false);
        return;
      }

      const json = await res.json();
      const publicUrl = json.data?.url || '';
      setPreviewUrl(publicUrl);
      setFormData(prev => ({ ...prev, image_url: publicUrl }));
      setUploading(false);
    } catch (error) {
      alert('图片上传失败');
      setUploading(false);
    }
  };

  // 删除图片
  const handleRemoveImage = () => {
    setPreviewUrl(null);
    setFormData(prev => ({ ...prev, image_url: undefined }));
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  // 触发文件选择
  const triggerFileSelect = () => {
    fileInputRef.current?.click();
  };

  const addYarnRatio = () => {
    setFormData(prev => ({
      ...prev,
      yarn_ratios: [...prev.yarn_ratios, { yarn_name: '', ratio: 100, yarn_type: 'all' }]
    }));
  };

  const removeYarnRatio = (index: number) => {
    setFormData(prev => ({
      ...prev,
      yarn_ratios: prev.yarn_ratios.filter((_, i) => i !== index)
    }));
  };

  const updateYarnRatio = (index: number, field: 'yarn_name' | 'ratio' | 'yarn_type', value: string | number) => {
    setFormData(prev => {
      const newRatios = [...prev.yarn_ratios];
      newRatios[index] = { ...newRatios[index], [field]: value };
      return { ...prev, yarn_ratios: newRatios };
    });
  };

  if (!isOpen) return null;

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4"
    >
      <motion.div
        initial={{ opacity: 0, scale: 0.95, y: 20 }}
        animate={{ opacity: 1, scale: 1, y: 0 }}
        exit={{ opacity: 0, scale: 0.95, y: 20 }}
        className={`bg-white rounded-2xl shadow-2xl ${isMobile ? 'w-full max-h-[90vh]' : 'w-[600px] max-h-[90vh]'} overflow-hidden`}
      >
        {/* 头部 */}
        <div className="flex items-center justify-between p-4 border-b border-gray-200 bg-gray-50">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 bg-gradient-to-br from-blue-500 to-indigo-500 rounded-xl flex items-center justify-center">
              <Package className="w-5 h-5 text-white" />
            </div>
            <div>
              <h3 className="text-lg font-semibold text-gray-900">
                {editingProduct ? '编辑产品' : '新建产品'}
              </h3>
              <p className="text-xs text-gray-500">
                {editingProduct ? '修改产品信息' : '添加新产品到仓库'}
              </p>
            </div>
          </div>
          <button
            onClick={onClose}
            className="p-2 hover:bg-gray-200 rounded-lg transition-colors"
          >
            <X className="w-5 h-5 text-gray-500" />
          </button>
        </div>

        {/* 内容 */}
        <div className="p-6 overflow-y-auto max-h-[60vh]">
          <div className="space-y-5">
            {/* 产品图片上传 */}
            <div>
              <label className="flex items-center gap-2 text-sm font-medium text-gray-700 mb-2">
                <ImageIcon className="w-4 h-4 text-gray-400" />
                产品图片
              </label>
              <input
                ref={fileInputRef}
                type="file"
                accept="image/*"
                onChange={handleImageSelect}
                className="hidden"
              />
              {previewUrl ? (
                <div className="relative">
                  <img
                    src={previewUrl}
                    alt="产品预览"
                    className="w-full h-40 object-cover rounded-xl border border-gray-200"
                  />
                  <div className="absolute top-2 right-2 flex gap-2">
                    <button
                      onClick={triggerFileSelect}
                      disabled={uploading}
                      className="p-2 bg-white/90 hover:bg-white rounded-lg shadow-md transition-colors"
                    >
                      <Upload className="w-4 h-4 text-gray-600" />
                    </button>
                    <button
                      onClick={handleRemoveImage}
                      className="p-2 bg-white/90 hover:bg-white rounded-lg shadow-md transition-colors"
                    >
                      <Trash2 className="w-4 h-4 text-red-500" />
                    </button>
                  </div>
                </div>
              ) : (
                <button
                  onClick={triggerFileSelect}
                  disabled={uploading}
                  className="w-full h-40 border-2 border-dashed border-gray-300 rounded-xl flex flex-col items-center justify-center gap-2 hover:border-blue-400 hover:bg-blue-50/50 transition-colors"
                >
                  {uploading ? (
                    <>
                      <div className="w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full animate-spin" />
                      <span className="text-sm text-gray-500">上传中...</span>
                    </>
                  ) : (
                    <>
                      <Upload className="w-8 h-8 text-gray-400" />
                      <span className="text-sm text-gray-500">点击上传产品图片</span>
                      <span className="text-xs text-gray-400">支持 JPG、PNG 格式，最大 5MB</span>
                    </>
                  )}
                </button>
              )}
            </div>

            {/* 三级结构：成品名称-颜色 */}
            <div className={`grid ${isMobile ? 'grid-cols-1 gap-4' : 'grid-cols-2 gap-4'}`}>
              {/* 成品名称 - 带搜索建议 */}
              <div className="product-search-container relative">
                <label className="flex items-center gap-2 text-sm font-medium text-gray-700 mb-2">
                  <Tag className="w-4 h-4 text-gray-400" />
                  成品名称
                  {isSearching && <span className="text-xs text-blue-500">搜索中...</span>}
                </label>
                <div className="relative">
                  <input
                    type="text"
                    value={formData.product_name}
                    onChange={e => handleProductNameChange(e.target.value)}
                    onFocus={() => {
                      // 聚焦时如果有输入内容，立即触发搜索显示建议
                      if (formData.product_name.length >= 1) {
                        searchProducts(formData.product_name);
                        setShowProductSuggestions(true);
                      }
                    }}
                    placeholder="如：水洗棉花糖"
                    className="w-full px-3 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"
                    autoComplete="off"
                  />
                  <Search className="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                </div>

                {/* 产品搜索建议下拉列表 */}
                {showProductSuggestions && productSuggestions.length > 0 && (
                  <motion.div
                    initial={{ opacity: 0, y: -10 }}
                    animate={{ opacity: 1, y: 0 }}
                    exit={{ opacity: 0, y: -10 }}
                    className="absolute z-50 left-0 right-0 mt-1 bg-white border border-gray-200 rounded-xl shadow-lg max-h-60 overflow-y-auto"
                  >
                    <div className="px-3 py-2 text-xs text-gray-500 border-b border-gray-100 bg-gray-50">
                      点击快速选择已有产品
                    </div>
                    {productSuggestions.map((suggestion) => (
                      <button
                        key={suggestion.id}
                        onClick={() => selectProductSuggestion(suggestion)}
                        className="w-full px-3 py-2.5 text-left hover:bg-blue-50 transition-colors border-b border-gray-50 last:border-b-0"
                      >
                        <div className="flex items-center justify-between">
                          <div>
                            <span className="text-sm font-medium text-gray-900">{suggestion.product_name}</span>
                            <span className="text-xs text-gray-500 ml-2">{suggestion.color}</span>
                          </div>
                          <div className="text-xs text-gray-500">
                            {suggestion.total_weight > 0 && `${suggestion.total_weight}g`}
                          </div>
                        </div>
                        <div className="text-xs text-gray-400 mt-0.5">
                          {suggestion.fabric_code}-{suggestion.color_code}
                        </div>
                      </button>
                    ))}
                  </motion.div>
                )}

                {/* 无搜索结果提示 */}
                {showProductSuggestions && formData.product_name.length >= 1 && productSuggestions.length === 0 && !isSearching && (
                  <div className="absolute z-50 left-0 right-0 mt-1 bg-white border border-gray-200 rounded-xl shadow-lg p-3 text-center">
                    <span className="text-sm text-gray-500">未找到匹配产品，将创建新产品</span>
                  </div>
                )}
              </div>
              <div>
                <label className="flex items-center gap-2 text-sm font-medium text-gray-700 mb-2">
                  <Palette className="w-4 h-4 text-gray-400" />
                  颜色
                </label>
                <input
                  type="text"
                  value={formData.color}
                  onChange={e => setFormData(prev => ({ ...prev, color: e.target.value }))}
                  placeholder="如：白色"
                  className="w-full px-3 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"
                />
              </div>
            </div>

            {/* 克重细分：经线克重、纬线克重、总克重 */}
            <div>
              <label className="flex items-center gap-2 text-sm font-medium text-gray-700 mb-2">
                <Hash className="w-4 h-4 text-gray-400" />
                克重（m/g）
              </label>
              <div className={`grid ${isMobile ? 'grid-cols-1 gap-3' : 'grid-cols-3 gap-3'}`}>
                <div>
                  <label className="text-xs text-gray-500 mb-1 block">经线克重</label>
                  <input
                    type="number"
                    inputMode="decimal"
                    value={formData.warp_weight}
                    onChange={e => {
                      const warpVal = e.target.value;
                      const weftVal = formData.weft_weight;
                      const warpNum = parseFloat(warpVal) || 0;
                      const weftNum = parseFloat(weftVal) || 0;
                      // 若经线和纬线都有值，自动计算总克重
                      const autoTotal = (warpNum > 0 && weftNum > 0) ? String(warpNum + weftNum) : formData.total_weight;
                      setFormData(prev => ({ ...prev, warp_weight: warpVal, total_weight: autoTotal }));
                    }}
                    placeholder="如：45"
                    className="w-full px-3 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"
                  />
                </div>
                <div>
                  <label className="text-xs text-gray-500 mb-1 block">纬线克重</label>
                  <input
                    type="number"
                    inputMode="decimal"
                    value={formData.weft_weight}
                    onChange={e => {
                      const weftVal = e.target.value;
                      const warpVal = formData.warp_weight;
                      const warpNum = parseFloat(warpVal) || 0;
                      const weftNum = parseFloat(weftVal) || 0;
                      // 若经线和纬线都有值，自动计算总克重
                      const autoTotal = (warpNum > 0 && weftNum > 0) ? String(warpNum + weftNum) : formData.total_weight;
                      setFormData(prev => ({ ...prev, weft_weight: weftVal, total_weight: autoTotal }));
                    }}
                    placeholder="如：45"
                    className="w-full px-3 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"
                  />
                </div>
                <div>
                  <label className="text-xs text-gray-500 mb-1 block">
                    总克重
                    {parseFloat(formData.warp_weight) > 0 && parseFloat(formData.weft_weight) > 0 && (
                      <span className="text-blue-500 ml-1">（自动计算）</span>
                    )}
                  </label>
                  <input
                    type="number"
                    inputMode="decimal"
                    value={formData.total_weight}
                    onChange={e => setFormData(prev => ({ ...prev, total_weight: e.target.value }))}
                    placeholder="如：90"
                    disabled={parseFloat(formData.warp_weight) > 0 && parseFloat(formData.weft_weight) > 0}
                    className="w-full px-3 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 disabled:bg-gray-50 disabled:text-gray-500"
                  />
                </div>
              </div>
              <p className="text-xs text-gray-400 mt-1.5">
                填写经线克重和纬线克重后，总克重将自动计算（经线+纬线）；若只填总克重则手动输入。
              </p>
            </div>

            {/* 产品码 */}
            <div>
              <label className="flex items-center gap-2 text-sm font-medium text-gray-700 mb-2">
                <Hash className="w-4 h-4 text-gray-400" />
                产品码
              </label>
              <input
                type="text"
                value={formData.fabric_code}
                onChange={e => setFormData(prev => ({ ...prev, fabric_code: e.target.value }))}
                placeholder="如：ST9001"
                className="w-full px-3 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 font-mono uppercase"
              />
              <p className="text-xs text-gray-400 mt-1">格式：字母+数字（如：ST9001）</p>
            </div>

            {/* 色号 */}
            <div>
              <label className="flex items-center gap-2 text-sm font-medium text-gray-700 mb-2">
                <Hash className="w-4 h-4 text-gray-400" />
                色号
              </label>
              <input
                type="text"
                value={formData.color_code}
                onChange={e => setFormData(prev => ({ ...prev, color_code: e.target.value }))}
                placeholder="如：01"
                className="w-full px-3 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"
              />
            </div>

            {/* 生产采购价 */}
            <div>
              <label className="flex items-center gap-2 text-sm font-medium text-gray-700 mb-2">
                <DollarSign className="w-4 h-4 text-gray-400" />
                生产采购价（元/米）
              </label>
              <input
                type="number"
                value={formData.production_price}
                onChange={e => setFormData(prev => ({ ...prev, production_price: e.target.value }))}
                placeholder="如：15.5"
                className="w-full px-3 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"
              />
            </div>

            {/* 纱线配比 */}
            <div>
              <label className="flex items-center gap-2 text-sm font-medium text-gray-700 mb-3">
                <Layers className="w-4 h-4 text-gray-400" />
                纱线名称/占比
              </label>
              <div className="space-y-3">
                {formData.yarn_ratios.map((ratio, index) => (
                  <div key={index} className={`flex gap-1.5 ${isMobile ? 'flex-col' : ''}`}>
                    {/* 纱线类型选择 */}
                    <select
                      value={ratio.yarn_type}
                      onChange={e => updateYarnRatio(index, 'yarn_type', e.target.value)}
                      className={`px-2.5 py-1.5 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all bg-white ${isMobile ? 'w-full' : 'w-20 flex-shrink-0'}`}
                    >
                      {yarnTypeOptions.map(option => (
                        <option key={option.value} value={option.value}>{option.label}</option>
                      ))}
                    </select>
                    <input
                      type="text"
                      value={ratio.yarn_name}
                      onChange={e => updateYarnRatio(index, 'yarn_name', e.target.value)}
                      placeholder="纱线名称"
                      className={`px-2.5 py-1.5 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all ${isMobile ? 'w-full' : 'flex-1 min-w-0'}`}
                    />
                    <div className={`flex items-center gap-0.5 ${isMobile ? 'w-full' : 'w-20 flex-shrink-0'}`}>
                      <input
                        type="number"
                        value={ratio.ratio}
                        onChange={e => updateYarnRatio(index, 'ratio', Number(e.target.value))}
                        placeholder="占比"
                        className="flex-1 min-w-0 px-2 py-1.5 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all"
                      />
                      <span className="text-sm text-gray-500 flex-shrink-0 w-3">%</span>
                    </div>
                    {formData.yarn_ratios.length > 1 && (
                      <button
                        onClick={() => removeYarnRatio(index)}
                        className={`px-2 py-1.5 text-red-500 hover:bg-red-50 rounded-lg transition-colors flex-shrink-0 ${isMobile ? 'w-full flex items-center justify-center gap-1' : ''}`}
                      >
                        <Minus className="w-4 h-4" />
                        {isMobile && <span className="text-sm">删除</span>}
                      </button>
                    )}
                  </div>
                ))}
              </div>
              <button
                onClick={addYarnRatio}
                className="mt-3 flex items-center gap-1 text-sm text-blue-600 hover:text-blue-700 font-medium transition-colors"
              >
                <Plus className="w-4 h-4" />
                添加纱线类型
              </button>
            </div>
          </div>
        </div>

        {/* 底部 */}
        <div className="flex gap-3 p-4 border-t border-gray-200 bg-gray-50">
          <button
            onClick={onClose}
            className={`py-2.5 border border-gray-300 rounded-xl text-gray-700 hover:bg-gray-100 font-medium transition-colors ${isMobile ? 'w-full' : 'flex-1'}`}
          >
            取消
          </button>
          <button
            onClick={() => onSave(formData)}
            className={`py-2.5 bg-gradient-to-r from-blue-500 to-indigo-500 text-white rounded-xl font-medium hover:from-blue-600 hover:to-indigo-600 transition-all shadow-md hover:shadow-lg ${isMobile ? 'w-full' : 'flex-1'}`}
          >
            确认保存
          </button>
        </div>
      </motion.div>
    </motion.div>
  );
}
