import React, { useState } from 'react';
import { exportMaterialsToExcel, createExcelBlob } from '../../../utils/excelExport';
import api from '../../../api';
import { FilterableHeader } from '../shared';

const ValveMaterialsView = ({ 
  materials, 
  selectedMaterials, 
  setSelectedMaterials,
  userRequirements,
  setUserRequirements,
  purchasedMaterials,
  onPurchasedMaterialsUpdate,
  updateMaterial, // 자재 업데이트 함수
  fileId,
  jobNo,
  user 
}) => {
  const [sortConfig, setSortConfig] = useState({ key: null, direction: 'asc' });
  const [columnFilters, setColumnFilters] = useState({});
  const [showFilterDropdown, setShowFilterDropdown] = useState(null);
  const [brandInputs, setBrandInputs] = useState({}); // 브랜드 입력 상태
  const [savingBrand, setSavingBrand] = useState({}); // 브랜드 저장 중 상태
  const [savingRequest, setSavingRequest] = useState({}); // 추가요구사항 저장 중 상태
  const [savedBrands, setSavedBrands] = useState({}); // 저장된 브랜드 상태
  const [savedRequests, setSavedRequests] = useState({}); // 저장된 추가요구사항 상태
  const [editingBrand, setEditingBrand] = useState({}); // 브랜드 편집 모드
  const [editingRequest, setEditingRequest] = useState({}); // 추가요구사항 편집 모드

  // 컴포넌트 마운트 시 저장된 데이터 로드
  React.useEffect(() => {
    const loadSavedData = () => {
      const savedBrandsData = {};
      const savedRequestsData = {};
      
      console.log('🔍 ValveMaterialsView useEffect 트리거됨:', materials.length, '개 자재');
      console.log('🔍 현재 materials 배열:', materials.map(m => ({id: m.id, brand: m.brand, user_requirement: m.user_requirement})));
      
      materials.forEach(material => {
        // 백엔드에서 가져온 데이터가 있으면 저장된 상태로 설정
        if (material.brand && material.brand.trim()) {
          savedBrandsData[material.id] = material.brand.trim();
          console.log('✅ 브랜드 로드됨:', material.id, '→', material.brand);
        }
        if (material.user_requirement && material.user_requirement.trim()) {
          savedRequestsData[material.id] = material.user_requirement.trim();
          console.log('✅ 요구사항 로드됨:', material.id, '→', material.user_requirement);
        }
      });
      
      console.log('💾 최종 저장된 브랜드:', savedBrandsData);
      console.log('💾 최종 저장된 요구사항:', savedRequestsData);
      
      // 상태 업데이트를 즉시 반영하기 위해 setTimeout 사용
      setSavedBrands(savedBrandsData);
      setSavedRequests(savedRequestsData);
      
      // 상태 업데이트 후 강제 리렌더링 확인
      setTimeout(() => {
        console.log('🔄 상태 업데이트 후 확인 - savedBrands:', savedBrandsData);
      }, 100);
    };

    console.log('🔄 ValveMaterialsView useEffect 실행 - materials 길이:', materials?.length || 0);
    
    if (materials && materials.length > 0) {
      loadSavedData();
    } else {
      console.log('⚠️ materials가 비어있거나 undefined');
      // 빈 상태로 초기화
      setSavedBrands({});
      setSavedRequests({});
    }
  }, [materials]);

  const parseValveInfo = (material) => {
    const valveDetails = material.valve_details || {};
    const description = material.original_description || '';
    const descUpper = description.toUpperCase();
    
    // 1. 벨브 타입 파싱 (한글명으로 표시)
    let valveType = '';
    if (descUpper.includes('SIGHT GLASS') || descUpper.includes('사이트글라스')) {
      valveType = 'SIGHT GLASS';
    } else if (descUpper.includes('STRAINER') || descUpper.includes('스트레이너')) {
      valveType = 'STRAINER';
    } else if (descUpper.includes('GATE') || descUpper.includes('게이트')) {
      valveType = 'GATE VALVE';
    } else if (descUpper.includes('BALL') || descUpper.includes('볼')) {
      valveType = 'BALL VALVE';
    } else if (descUpper.includes('CHECK') || descUpper.includes('체크')) {
      valveType = 'CHECK VALVE';
    } else if (descUpper.includes('GLOBE') || descUpper.includes('글로브')) {
      valveType = 'GLOBE VALVE';
    } else if (descUpper.includes('BUTTERFLY') || descUpper.includes('버터플라이')) {
      valveType = 'BUTTERFLY VALVE';
    } else if (descUpper.includes('NEEDLE') || descUpper.includes('니들')) {
      valveType = 'NEEDLE VALVE';
    } else if (descUpper.includes('RELIEF') || descUpper.includes('릴리프')) {
      valveType = 'RELIEF VALVE';
    } else {
      valveType = 'VALVE';
    }
    
    // 2. 사이즈 정보
    const size = material.main_nom || material.size_inch || material.size_spec || '-';
    
    // 3. 압력 등급
    const pressure = material.pressure_rating || 
      (descUpper.match(/(\d+)\s*LB/) ? descUpper.match(/(\d+)\s*LB/)[0] : '-');
    
    // 4. 브랜드 (사용자 입력 가능)
    const brand = '-'; // 기본값, 사용자가 입력할 수 있도록
    
    // 5. 추가 정보 추출 (3-WAY, DOUL PLATE, DOUBLE DISC 등)
    let additionalInfo = '';
    const additionalPatterns = [
      '3-WAY', '3WAY', 'THREE WAY',
      'DOUL PLATE', 'DOUBLE PLATE', 'DUAL PLATE',
      'DOUBLE DISC', 'DUAL DISC',
      'SWING', 'LIFT', 'TILTING',
      'WAFER', 'LUG', 'FLANGED',
      'FULL BORE', 'REDUCED BORE',
      'FIRE SAFE', 'ANTI STATIC'
    ];
    
    for (const pattern of additionalPatterns) {
      if (descUpper.includes(pattern)) {
        if (additionalInfo) {
          additionalInfo += ', ';
        }
        additionalInfo += pattern;
      }
    }
    
    if (!additionalInfo) {
      additionalInfo = '-';
    }
    
    // 6. 연결 방식 (투입구/Connection Type)
    let connectionType = '';
    if (descUpper.includes('SW X THRD') || descUpper.includes('SW×THRD')) {
      connectionType = 'SW×THRD';
    } else if (descUpper.includes('FLG') || descUpper.includes('FLANGE')) {
      connectionType = 'FLG';
    } else if (descUpper.includes('SW') || descUpper.includes('SOCKET')) {
      connectionType = 'SW';
    } else if (descUpper.includes('THRD') || descUpper.includes('THREAD')) {
      connectionType = 'THRD';
    } else if (descUpper.includes('BW') || descUpper.includes('BUTT WELD')) {
      connectionType = 'BW';
    } else {
      connectionType = '-';
    }
    
    // 7. 구매 수량 계산 (기본 수량 그대로)
    const qty = Math.round(material.quantity || 0);
    const purchaseQuantity = `${qty} EA`;
    
    return {
      type: valveType, // 벨브 종류만 (GATE VALVE, BALL VALVE 등)
      size: size,
      pressure: pressure,
      brand: brand, // 브랜드 (사용자 입력 가능)
      additionalInfo: additionalInfo, // 추가 정보 (3-WAY, DOUL PLATE 등)
      connection: connectionType, // 투입구/연결방식 (SW, FLG 등)
      additionalRequest: '-', // 추가 요구사항 (기존 User Requirement)
      purchaseQuantity: purchaseQuantity,
      originalQuantity: qty,
      isValve: true
    };
  };

  // 정렬 처리
  const handleSort = (key) => {
    let direction = 'asc';
    if (sortConfig.key === key && sortConfig.direction === 'asc') {
      direction = 'desc';
    }
    setSortConfig({ key, direction });
  };

  // 필터링된 및 정렬된 자재 목록
  const getFilteredAndSortedMaterials = () => {
    let filtered = materials.filter(material => {
      return Object.entries(columnFilters).every(([key, filterValue]) => {
        if (!filterValue) return true;
        const info = parseValveInfo(material);
        const value = info[key]?.toString().toLowerCase() || '';
        return value.includes(filterValue.toLowerCase());
      });
    });

    if (sortConfig && sortConfig.key) {
      filtered.sort((a, b) => {
        const aInfo = parseValveInfo(a);
        const bInfo = parseValveInfo(b);
        
        if (!aInfo || !bInfo) return 0;
        
        const aValue = aInfo[sortConfig.key];
        const bValue = bInfo[sortConfig.key];
        
        // 값이 없는 경우 처리
        if (aValue === undefined && bValue === undefined) return 0;
        if (aValue === undefined) return 1;
        if (bValue === undefined) return -1;
        
        // 숫자인 경우 숫자로 비교
        if (typeof aValue === 'number' && typeof bValue === 'number') {
          return sortConfig.direction === 'asc' ? aValue - bValue : bValue - aValue;
        }
        
        // 문자열로 비교
        const aStr = String(aValue).toLowerCase();
        const bStr = String(bValue).toLowerCase();
        
        if (sortConfig.direction === 'asc') {
          return aStr.localeCompare(bStr);
        } else {
          return bStr.localeCompare(aStr);
        }
      });
    }

    return filtered;
  };

  // 전체 선택/해제 (구매신청된 자재 제외)
  // 브랜드 저장 함수
  const handleSaveBrand = async (materialId, brand) => {
    if (!brand.trim()) return;
    
    setSavingBrand(prev => ({ ...prev, [materialId]: true }));
    try {
      await api.patch(`/materials/${materialId}/brand`, { brand: brand.trim() });
      // 성공 시 저장된 상태로 전환
      setSavedBrands(prev => ({ ...prev, [materialId]: brand.trim() }));
      setEditingBrand(prev => ({ ...prev, [materialId]: false }));
      setBrandInputs(prev => ({ ...prev, [materialId]: '' })); // 입력 필드 초기화
      
      // materials 배열도 업데이트 (카테고리 변경 시 데이터 유지를 위해)
      if (updateMaterial) {
        updateMaterial(materialId, { brand: brand.trim() });
        console.log('✅ materials 배열 업데이트 완료:', materialId, '→', brand.trim());
      }
    } catch (error) {
      console.error('브랜드 저장 실패:', error);
      alert('브랜드 저장에 실패했습니다.');
    } finally {
      setSavingBrand(prev => ({ ...prev, [materialId]: false }));
    }
  };

  // 브랜드 편집 시작
  const handleEditBrand = (materialId, currentBrand) => {
    setEditingBrand(prev => ({ ...prev, [materialId]: true }));
    setBrandInputs(prev => ({ ...prev, [materialId]: currentBrand || '' }));
  };

  // 추가요구사항 저장 함수
  const handleSaveRequest = async (materialId, request) => {
    setSavingRequest(prev => ({ ...prev, [materialId]: true }));
    try {
      await api.patch(`/materials/${materialId}/user-requirement`, { 
        user_requirement: request.trim() 
      });
      // 성공 시 저장된 상태로 전환
      setSavedRequests(prev => ({ ...prev, [materialId]: request.trim() }));
      setEditingRequest(prev => ({ ...prev, [materialId]: false }));
      setUserRequirements(prev => ({ ...prev, [materialId]: '' })); // 입력 필드 초기화
      
      // materials 배열도 업데이트 (카테고리 변경 시 데이터 유지를 위해)
      if (updateMaterial) {
        updateMaterial(materialId, { user_requirement: request.trim() });
        console.log('✅ materials 배열 업데이트 완료:', materialId, '→', request.trim());
      }
    } catch (error) {
      console.error('추가요구사항 저장 실패:', error);
      alert('추가요구사항 저장에 실패했습니다.');
    } finally {
      setSavingRequest(prev => ({ ...prev, [materialId]: false }));
    }
  };

  // 추가요구사항 편집 시작
  const handleEditRequest = (materialId, currentRequest) => {
    setEditingRequest(prev => ({ ...prev, [materialId]: true }));
    setUserRequirements(prev => ({ ...prev, [materialId]: currentRequest || '' }));
  };

  const handleSelectAll = () => {
    const filteredMaterials = getFilteredAndSortedMaterials();
    const selectableMaterials = filteredMaterials.filter(m => !purchasedMaterials.has(m.id));
    
    if (selectedMaterials.size === selectableMaterials.length) {
      setSelectedMaterials(new Set());
    } else {
      setSelectedMaterials(new Set(selectableMaterials.map(m => m.id)));
    }
  };

  // 개별 선택 (구매신청된 자재는 선택 불가)
  const handleMaterialSelect = (materialId) => {
    if (purchasedMaterials.has(materialId)) {
      return; // 구매신청된 자재는 선택 불가
    }
    
    const newSelected = new Set(selectedMaterials);
    if (newSelected.has(materialId)) {
      newSelected.delete(materialId);
    } else {
      newSelected.add(materialId);
    }
    setSelectedMaterials(newSelected);
  };

  // 엑셀 내보내기
  const handleExportToExcel = async () => {
    const selectedMaterialsData = materials.filter(m => selectedMaterials.has(m.id));
    if (selectedMaterialsData.length === 0) {
      alert('내보낼 자재를 선택해주세요.');
      return;
    }

    const timestamp = new Date().toISOString().slice(0, 19).replace(/:/g, '-');
    const excelFileName = `VALVE_Materials_${timestamp}.xlsx`;

    const dataWithRequirements = selectedMaterialsData.map(material => ({
      ...material,
      user_requirement: savedRequests[material.id] || userRequirements[material.id] || ''
    }));

    try {
      console.log('🔄 밸브 엑셀 내보내기 시작 - 새로운 방식');
      
      // 1. 먼저 클라이언트에서 엑셀 파일 생성
      console.log('📊 엑셀 Blob 생성 중...', dataWithRequirements.length, '개 자료');
      const excelBlob = await createExcelBlob(dataWithRequirements, excelFileName, {
        category: 'VALVE',
        filename: excelFileName,
        uploadDate: new Date().toLocaleDateString()
      });
      console.log('✅ 엑셀 Blob 생성 완료:', excelBlob.size, 'bytes');

      // 2. 구매신청 생성
      const allMaterialIds = selectedMaterialsData.map(m => m.id);
      const response = await api.post('/purchase-request/create', {
        file_id: fileId,
        job_no: jobNo,
        category: 'VALVE',
        material_ids: allMaterialIds,
        materials_data: dataWithRequirements.map(m => ({
          material_id: m.id,
          description: m.original_description,
          category: m.classified_category,
          size: m.size_inch || m.size_spec,
          schedule: m.schedule,
          material_grade: m.material_grade || m.full_material_grade,
          quantity: m.quantity,
          unit: m.unit,
          user_requirement: userRequirements[m.id] || ''
        }))
      });

      if (response.data.success) {
        console.log(`✅ 구매신청 완료: ${response.data.request_no}, request_id: ${response.data.request_id}`);
        
        // 3. 생성된 엑셀 파일을 서버에 업로드
        console.log('📤 서버에 엑셀 파일 업로드 중...');
        const formData = new FormData();
        formData.append('excel_file', excelBlob, excelFileName);
        formData.append('request_id', response.data.request_id);
        formData.append('category', 'VALVE');
        
        const uploadResponse = await api.post('/purchase-request/upload-excel', formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        });
        console.log('✅ 엑셀 업로드 완료:', uploadResponse.data);

        if (onPurchasedMaterialsUpdate) {
          onPurchasedMaterialsUpdate(allMaterialIds);
        }
      }

      // 4. 클라이언트 다운로드
      const url = window.URL.createObjectURL(excelBlob);
      const link = document.createElement('a');
      link.href = url;
      link.download = excelFileName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);

      alert(`구매신청 ${response.data?.request_no || ''}이 생성되고 엑셀 파일이 저장되었습니다.`);
    } catch (error) {
      console.error('엑셀 저장 또는 구매신청 실패:', error);
      // 실패 시에도 클라이언트 다운로드는 진행
      exportMaterialsToExcel(dataWithRequirements, excelFileName, {
        category: 'VALVE',
        filename: excelFileName,
        uploadDate: new Date().toLocaleDateString()
      });
      alert('엑셀 파일은 다운로드되었지만 구매신청 생성에 실패했습니다.');
    }
  };

  const filteredMaterials = getFilteredAndSortedMaterials();

  return (
    <div style={{ padding: '32px' }}>
      {/* 헤더 */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '24px' }}>
        <div>
          <h3 style={{ 
            fontSize: '24px', 
            fontWeight: '700', 
            color: '#0f172a', 
            margin: '0 0 8px 0' 
          }}>
            Valve Materials
          </h3>
          <p style={{ 
            fontSize: '14px', 
            color: '#64748b', 
            margin: 0 
          }}>
            {filteredMaterials.length} items • {selectedMaterials.size} selected
          </p>
        </div>
        
        <div style={{ display: 'flex', gap: '12px' }}>
          <button
            onClick={handleSelectAll}
            style={{
              background: 'white',
              color: '#6b7280',
              border: '1px solid #d1d5db',
              borderRadius: '8px',
              padding: '10px 16px',
              cursor: 'pointer',
              fontSize: '14px',
              fontWeight: '500'
            }}
          >
            {selectedMaterials.size === filteredMaterials.length ? 'Deselect All' : 'Select All'}
          </button>
        
        <button
          onClick={handleExportToExcel}
          disabled={selectedMaterials.size === 0}
          style={{
            background: selectedMaterials.size > 0 ? 'linear-gradient(135deg, #ef4444 0%, #dc2626 100%)' : '#e5e7eb',
            color: selectedMaterials.size > 0 ? 'white' : '#9ca3af',
            border: 'none',
            borderRadius: '8px',
            padding: '10px 16px',
            cursor: selectedMaterials.size > 0 ? 'pointer' : 'not-allowed',
            fontSize: '14px',
            fontWeight: '500'
          }}
        >
          Export to Excel ({selectedMaterials.size})
        </button>
      </div>
            </div>

      {/* 테이블 */}
      <div style={{ 
        background: 'white', 
        borderRadius: '12px', 
        overflow: 'auto',
        boxShadow: '0 1px 3px rgba(0, 0, 0, 0.1)',
        maxHeight: '600px'
      }}>
        <div style={{ minWidth: '1600px' }}>
          {/* 헤더 */}
          <div style={{
            display: 'grid',
            gridTemplateColumns: '50px 200px 120px 120px 150px 180px 180px 150px 200px',
            gap: '16px',
            padding: '16px',
            background: '#f8fafc',
            borderBottom: '1px solid #e2e8f0',
            fontSize: '14px',
            fontWeight: '600',
            color: '#374151',
            textAlign: 'center'
          }}>
          <div>
            <input
              type="checkbox"
              checked={(() => {
                const selectableMaterials = filteredMaterials.filter(m => !purchasedMaterials.has(m.id));
                return selectedMaterials.size === selectableMaterials.length && selectableMaterials.length > 0;
              })()}
              onChange={handleSelectAll}
              style={{ cursor: 'pointer' }}
            />
          </div>
          <FilterableHeader 
            sortKey="type" 
            filterKey="type"
            sortConfig={sortConfig}
            onSort={handleSort}
            columnFilters={columnFilters}
            onFilterChange={setColumnFilters}
            showFilterDropdown={showFilterDropdown}
            setShowFilterDropdown={setShowFilterDropdown}
          >
            Type
          </FilterableHeader>
          <FilterableHeader 
            sortKey="size" 
            filterKey="size"
            sortConfig={sortConfig}
            onSort={handleSort}
            columnFilters={columnFilters}
            onFilterChange={setColumnFilters}
            showFilterDropdown={showFilterDropdown}
            setShowFilterDropdown={setShowFilterDropdown}
          >
            Size
          </FilterableHeader>
          <FilterableHeader 
            sortKey="pressure" 
            filterKey="pressure"
            sortConfig={sortConfig}
            onSort={handleSort}
            columnFilters={columnFilters}
            onFilterChange={setColumnFilters}
            showFilterDropdown={showFilterDropdown}
            setShowFilterDropdown={setShowFilterDropdown}
          >
            Pressure
          </FilterableHeader>
          <div>Brand</div>
          <FilterableHeader 
            sortKey="additionalInfo" 
            filterKey="additionalInfo"
            sortConfig={sortConfig}
            onSort={handleSort}
            columnFilters={columnFilters}
            onFilterChange={setColumnFilters}
            showFilterDropdown={showFilterDropdown}
            setShowFilterDropdown={setShowFilterDropdown}
          >
            Additional Info
          </FilterableHeader>
          <FilterableHeader 
            sortKey="connection" 
            filterKey="connection"
            sortConfig={sortConfig}
            onSort={handleSort}
            columnFilters={columnFilters}
            onFilterChange={setColumnFilters}
            showFilterDropdown={showFilterDropdown}
            setShowFilterDropdown={setShowFilterDropdown}
          >
            Connection
          </FilterableHeader>
          <div>Additional Request</div>
          <FilterableHeader 
            sortKey="purchaseQuantity" 
            filterKey="purchaseQuantity"
            sortConfig={sortConfig}
            onSort={handleSort}
            columnFilters={columnFilters}
            onFilterChange={setColumnFilters}
            showFilterDropdown={showFilterDropdown}
            setShowFilterDropdown={setShowFilterDropdown}
          >
            Purchase Quantity
          </FilterableHeader>
        </div>

        {/* 데이터 행들 */}
        {filteredMaterials.map((material, index) => {
            const info = parseValveInfo(material);
            const isSelected = selectedMaterials.has(material.id);
            const isPurchased = purchasedMaterials.has(material.id);
            
            return (
              <div
                key={material.id}
                style={{
                display: 'grid',
                gridTemplateColumns: '50px 200px 120px 120px 150px 180px 180px 150px 200px',
                gap: '16px',
                  padding: '16px',
                borderBottom: index < filteredMaterials.length - 1 ? '1px solid #f1f5f9' : 'none',
                background: isSelected ? '#eff6ff' : (isPurchased ? '#fef3c7' : 'white'),
                transition: 'background 0.15s ease',
                textAlign: 'center'
              }}
              onMouseEnter={(e) => {
                if (!isSelected && !isPurchased) {
                  e.target.style.background = '#f8fafc';
                }
              }}
              onMouseLeave={(e) => {
                if (!isSelected && !isPurchased) {
                  e.target.style.background = 'white';
                }
              }}
            >
              <div>
                <input
                  type="checkbox"
                  checked={isSelected}
                  onChange={() => handleMaterialSelect(material.id)}
                  disabled={isPurchased}
                  style={{ 
                    cursor: isPurchased ? 'not-allowed' : 'pointer',
                    opacity: isPurchased ? 0.5 : 1
                  }}
                />
                  </div>
              <div style={{ fontSize: '14px', color: '#1f2937', fontWeight: '500' }}>
                {info.type}
                {isPurchased && (
                  <span style={{
                    marginLeft: '8px',
                    padding: '2px 6px',
                    background: '#fbbf24',
                    color: '#92400e',
                    borderRadius: '4px',
                    fontSize: '10px',
                    fontWeight: '500'
                  }}>
                    PURCHASED
                  </span>
                )}
              </div>
              <div style={{ fontSize: '14px', color: '#1f2937' }}>{info.size}</div>
              <div style={{ fontSize: '14px', color: '#1f2937' }}>{info.pressure}</div>
              <div style={{ display: 'flex', gap: '4px', alignItems: 'center' }}>
                {(() => {
                  // 디버깅: 렌더링 시점의 상태 확인
                  const hasEditingBrand = !!editingBrand[material.id];
                  const hasSavedBrand = !!savedBrands[material.id];
                  const shouldShowSaved = !hasEditingBrand && hasSavedBrand;
                  
                  if (material.id === 11789) { // 테스트 자재만 로그
                    console.log(`🎨 UI 렌더링 - ID ${material.id}:`, {
                      editingBrand: hasEditingBrand,
                      savedBrandExists: hasSavedBrand,
                      savedBrandValue: savedBrands[material.id],
                      shouldShowSaved: shouldShowSaved,
                      allSavedBrands: Object.keys(savedBrands),
                      renderingMode: shouldShowSaved ? 'SAVED_VIEW' : 'INPUT_VIEW'
                    });
                  }
                  
                  // 명시적으로 boolean 반환
                  return shouldShowSaved ? true : false;
                })() ? (
                  // 저장된 상태 - 브랜드 표시 + 수정 버튼
                  <>
                    <div style={{
                      flex: 1,
                      padding: '6px',
                      border: '1px solid #e5e7eb',
                      borderRadius: '4px',
                      fontSize: '11px',
                      textAlign: 'center',
                      background: '#f9fafb',
                      color: '#374151'
                    }}>
                      {savedBrands[material.id]}
                    </div>
                    <button
                      onClick={() => handleEditBrand(material.id, savedBrands[material.id])}
                      disabled={isPurchased}
                      style={{
                        padding: '6px 8px',
                        border: 'none',
                        borderRadius: '4px',
                        background: isPurchased ? '#d1d5db' : '#f59e0b',
                        color: 'white',
                        fontSize: '10px',
                        cursor: isPurchased ? 'not-allowed' : 'pointer',
                        opacity: isPurchased ? 0.5 : 1,
                        minWidth: '40px'
                      }}
                    >
                      Edit
                    </button>
                  </>
                ) : (
                  // 편집 상태 - 입력 필드 + 저장 버튼
                  <>
                    <input
                      type="text"
                      value={brandInputs[material.id] || ''}
                      onChange={(e) => setBrandInputs({
                        ...brandInputs,
                        [material.id]: e.target.value
                      })}
                      placeholder="Enter brand..."
                      disabled={isPurchased}
                      style={{
                        flex: 1,
                        padding: '6px',
                        border: '1px solid #d1d5db',
                        borderRadius: '4px',
                        fontSize: '11px',
                        textAlign: 'center',
                        opacity: isPurchased ? 0.5 : 1,
                        cursor: isPurchased ? 'not-allowed' : 'text'
                      }}
                    />
                    <button
                      onClick={() => handleSaveBrand(material.id, brandInputs[material.id] || '')}
                      disabled={isPurchased || savingBrand[material.id] || !brandInputs[material.id]?.trim()}
                      style={{
                        padding: '6px 8px',
                        border: 'none',
                        borderRadius: '4px',
                        background: isPurchased ? '#d1d5db' : '#3b82f6',
                        color: 'white',
                        fontSize: '10px',
                        cursor: isPurchased || savingBrand[material.id] ? 'not-allowed' : 'pointer',
                        opacity: isPurchased || !brandInputs[material.id]?.trim() ? 0.5 : 1,
                        minWidth: '40px'
                      }}
                    >
                      {savingBrand[material.id] ? '...' : 'Save'}
                    </button>
                  </>
                )}
              </div>
              <div style={{ fontSize: '14px', color: '#1f2937' }}>{info.additionalInfo}</div>
              <div style={{ fontSize: '14px', color: '#1f2937' }}>{info.connection}</div>
              <div style={{ display: 'flex', gap: '4px', alignItems: 'center' }}>
                {!editingRequest[material.id] && savedRequests[material.id] ? (
                  // 저장된 상태 - 요구사항 표시 + 수정 버튼
                  <>
                    <div style={{
                      flex: 1,
                      padding: '6px',
                      border: '1px solid #e5e7eb',
                      borderRadius: '4px',
                      fontSize: '11px',
                      background: '#f9fafb',
                      color: '#374151'
                    }}>
                      {savedRequests[material.id]}
                    </div>
                    <button
                      onClick={() => handleEditRequest(material.id, savedRequests[material.id])}
                      disabled={isPurchased}
                      style={{
                        padding: '6px 8px',
                        border: 'none',
                        borderRadius: '4px',
                        background: isPurchased ? '#d1d5db' : '#f59e0b',
                        color: 'white',
                        fontSize: '10px',
                        cursor: isPurchased ? 'not-allowed' : 'pointer',
                        opacity: isPurchased ? 0.5 : 1,
                        minWidth: '40px'
                      }}
                    >
                      Edit
                    </button>
                  </>
                ) : (
                  // 편집 상태 - 입력 필드 + 저장 버튼
                  <>
                    <input
                      type="text"
                      value={userRequirements[material.id] || ''}
                      onChange={(e) => setUserRequirements({
                        ...userRequirements,
                        [material.id]: e.target.value
                      })}
                      placeholder="Enter additional request..."
                      disabled={isPurchased}
                      style={{
                        flex: 1,
                        padding: '6px',
                        border: '1px solid #d1d5db',
                        borderRadius: '4px',
                        fontSize: '11px',
                        opacity: isPurchased ? 0.5 : 1,
                        cursor: isPurchased ? 'not-allowed' : 'text'
                      }}
                    />
                    <button
                      onClick={() => handleSaveRequest(material.id, userRequirements[material.id] || '')}
                      disabled={isPurchased || savingRequest[material.id]}
                      style={{
                        padding: '6px 8px',
                        border: 'none',
                        borderRadius: '4px',
                        background: isPurchased ? '#d1d5db' : '#10b981',
                        color: 'white',
                        fontSize: '10px',
                        cursor: isPurchased || savingRequest[material.id] ? 'not-allowed' : 'pointer',
                        opacity: isPurchased ? 0.5 : 1,
                        minWidth: '40px'
                      }}
                    >
                      {savingRequest[material.id] ? '...' : 'Save'}
                    </button>
                  </>
                )}
              </div>
              <div style={{ fontSize: '14px', color: '#1f2937' }}>{info.purchaseQuantity}</div>
              </div>
            );
          })}
        </div>
      </div>

      {filteredMaterials.length === 0 && (
        <div style={{
          textAlign: 'center',
          padding: '60px 20px',
          color: '#64748b'
        }}>
          <div style={{ fontSize: '18px', fontWeight: '600', marginBottom: '8px' }}>
            No Valve Materials Found
          </div>
          <div style={{ fontSize: '14px' }}>
            {Object.keys(columnFilters).some(key => columnFilters[key]) 
              ? 'Try adjusting your filters' 
              : 'No valve materials available in this BOM'}
          </div>
        </div>
      )}
    </div>
  );
};

export default ValveMaterialsView;
