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

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

  // 컴포넌트 마운트 시 저장된 데이터 로드
  React.useEffect(() => {
    const loadSavedData = () => {
      const savedRequestsData = {};
      
      materials.forEach(material => {
        if (material.user_requirement && material.user_requirement.trim()) {
          savedRequestsData[material.id] = material.user_requirement.trim();
        }
      });
      
      setSavedRequests(savedRequestsData);
    };

    if (materials && materials.length > 0) {
      loadSavedData();
    } else {
      setSavedRequests({});
    }
  }, [materials]);

  // 추가요구사항 저장 함수
  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]: '' }));
      
      if (updateMaterial) {
        updateMaterial(materialId, { user_requirement: 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 parseSupportInfo = (material) => {
    const desc = material.original_description || '';
    const descUpper = desc.toUpperCase();
    
    // 서포트 타입 분류 (백엔드 분류기와 동일한 로직)
    let supportType = 'U-BOLT'; // 기본값
    
    if (descUpper.includes('URETHANE') || descUpper.includes('BLOCK SHOE') || descUpper.includes('우레탄')) {
      supportType = 'URETHANE BLOCK SHOE';
    } else if (descUpper.includes('CLAMP') || descUpper.includes('클램프')) {
      // 클램프 타입 상세 분류 (CL-1, CL-2, CL-3 등)
      const clampMatch = desc.match(/CL[-\s]*(\d+)/i);
      if (clampMatch) {
        supportType = `CLAMP CL-${clampMatch[1]}`;
      } else {
        supportType = 'CLAMP CL-1'; // 기본값
      }
    } else if (descUpper.includes('HANGER') || descUpper.includes('행거')) {
      supportType = 'HANGER';
    } else if (descUpper.includes('SPRING') || descUpper.includes('스프링')) {
      supportType = 'SPRING HANGER';
    } else if (descUpper.includes('GUIDE') || descUpper.includes('가이드')) {
      supportType = 'GUIDE';
    } else if (descUpper.includes('ANCHOR') || descUpper.includes('앵커')) {
      supportType = 'ANCHOR';
    }
    
    // User Requirements 추출 (분류기에서 제공된 것 우선)
    const userRequirements = material.user_requirements || [];
    
    // 구매 수량 계산 (서포트는 취합된 숫자 그대로)
    const qty = Math.round(material.quantity || 0);
    const purchaseQty = qty;
    
    // Material Grade 처리 - 우레탄 블럭슈의 경우 두께 정보 포함
    let materialGrade = material.full_material_grade || material.material_grade || '-';
    
    if (supportType === 'URETHANE BLOCK SHOE') {
      // 두께 정보 추출 (40t, 27t 등 - 여기서 t는 thickness를 의미)
      const thicknessMatch = desc.match(/(\d+)\s*[tT]/);
      if (thicknessMatch) {
        const thickness = `${thicknessMatch[1]}t`;
        if (materialGrade === '-' || !materialGrade) {
          materialGrade = thickness;
        } else if (!materialGrade.includes(thickness)) {
          materialGrade = `${materialGrade} ${thickness}`;
        }
      }
    }
    
    return {
      type: supportType,
      size: material.main_nom || material.size_inch || material.size_spec || '-',
      grade: materialGrade,
      userRequirements: userRequirements.join(', ') || '-',
      additionalReq: '-',
      purchaseQuantity: `${purchaseQty} EA`,
      originalQuantity: qty,
      isSupport: true
    };
  };

  // 동일한 서포트 항목 합산
  const consolidateSupportMaterials = (materials) => {
    const consolidated = {};
    
    materials.forEach(material => {
      const info = parseSupportInfo(material);
      const key = `${info.type}|${info.size}|${info.grade}`;
      
      if (!consolidated[key]) {
        consolidated[key] = {
          ...material,
          // Material Grade 정보를 parsedInfo에서 가져와서 설정
          material_grade: info.grade,
          full_material_grade: info.grade,
          consolidatedQuantity: info.originalQuantity,
          consolidatedIds: [material.id],
          parsedInfo: info
        };
      } else {
        consolidated[key].consolidatedQuantity += info.originalQuantity;
        consolidated[key].consolidatedIds.push(material.id);
      }
    });
    
    // 합산된 수량으로 구매 수량 재계산 (서포트는 취합된 숫자 그대로)
    return Object.values(consolidated).map(item => {
      const purchaseQty = item.consolidatedQuantity;
      
      return {
        ...item,
        parsedInfo: {
          ...item.parsedInfo,
          originalQuantity: item.consolidatedQuantity,
          purchaseQuantity: `${purchaseQty} EA`
        }
      };
    });
  };

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

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

    // 정렬
    if (sortConfig && sortConfig.key) {
      filtered.sort((a, b) => {
        const aInfo = a.parsedInfo;
        const bInfo = b.parsedInfo;
        
        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 handleSelectAll = () => {
    const filteredMaterials = getFilteredAndSortedMaterials();
    const selectableMaterials = filteredMaterials.filter(material => 
      !material.consolidatedIds.some(id => purchasedMaterials.has(id))
    );
    
    if (selectedMaterials.size === selectableMaterials.flatMap(m => m.consolidatedIds).length) {
      setSelectedMaterials(new Set());
    } else {
      const allIds = selectableMaterials.flatMap(m => m.consolidatedIds);
      setSelectedMaterials(new Set(allIds));
    }
  };

  // 개별 선택 (구매신청된 자재는 선택 불가)
  const handleMaterialSelect = (consolidatedMaterial) => {
    const hasAnyPurchased = consolidatedMaterial.consolidatedIds.some(id => purchasedMaterials.has(id));
    if (hasAnyPurchased) {
      return; // 구매신청된 자재가 포함된 경우 선택 불가
    }
    
    const newSelected = new Set(selectedMaterials);
    const allSelected = consolidatedMaterial.consolidatedIds.every(id => newSelected.has(id));
    
    if (allSelected) {
      // 모두 선택된 경우 모두 해제
      consolidatedMaterial.consolidatedIds.forEach(id => newSelected.delete(id));
    } else {
      // 일부 또는 전체 미선택인 경우 모두 선택
      consolidatedMaterial.consolidatedIds.forEach(id => newSelected.add(id));
    }
    setSelectedMaterials(newSelected);
  };

  // 엑셀 내보내기
  const handleExportToExcel = async () => {
    // 선택된 합산 자료 가져오기
    const filteredMaterials = getFilteredAndSortedMaterials();
    const selectedConsolidatedMaterials = filteredMaterials.filter(consolidatedMaterial => 
      consolidatedMaterial.consolidatedIds.some(id => selectedMaterials.has(id))
    );
    
    if (selectedConsolidatedMaterials.length === 0) {
      alert('내보낼 자재를 선택해주세요.');
      return;
    }

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

    // 합산된 자료를 엑셀 형태로 변환
    const dataWithRequirements = selectedConsolidatedMaterials.map(consolidatedMaterial => ({
      ...consolidatedMaterial,
      // 합산된 수량으로 덮어쓰기
      quantity: consolidatedMaterial.consolidatedQuantity,
      // 사용자 요구사항은 대표 ID 기준 (저장된 데이터 우선)
      user_requirement: savedRequests[consolidatedMaterial.id] || userRequirements[consolidatedMaterial.id] || ''
    }));

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

      // 2. 구매신청 생성
      const allMaterialIds = selectedConsolidatedMaterials.flatMap(cm => cm.consolidatedIds);
      const response = await api.post('/purchase-request/create', {
        file_id: fileId,
        job_no: jobNo,
        category: 'SUPPORT',
        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. 엑셀 파일을 서버에 업로드
        const formData = new FormData();
        formData.append('excel_file', excelBlob, excelFileName);
        formData.append('request_id', response.data.request_id);
        formData.append('category', 'SUPPORT');
        
        console.log('📤 엑셀 파일 서버 업로드 중...');
        await api.post('/purchase-request/upload-excel', formData, {
          headers: { 'Content-Type': 'multipart/form-data' }
        });
        console.log('✅ 엑셀 파일 서버 업로드 완료');

        // 4. 구매된 자재 목록 업데이트 (비활성화)
        onPurchasedMaterialsUpdate(allMaterialIds);
        console.log('✅ 구매된 자재 목록 업데이트 완료');

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

    // 선택 해제
    setSelectedMaterials(new Set());
  };

  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' 
          }}>
            Support 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, #f97316 0%, #ea580c 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: '1200px' }}>
          {/* 헤더 */}
          <div style={{
            display: 'grid',
            gridTemplateColumns: '50px 200px 120px 150px 180px 200px 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(material => 
                  !material.consolidatedIds.some(id => purchasedMaterials.has(id))
                );
                return selectedMaterials.size === selectableMaterials.flatMap(m => m.consolidatedIds).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="grade" 
            filterKey="grade"
            sortConfig={sortConfig}
            onSort={handleSort}
            columnFilters={columnFilters}
            onFilterChange={setColumnFilters}
            showFilterDropdown={showFilterDropdown}
            setShowFilterDropdown={setShowFilterDropdown}
          >
            Material Grade
          </FilterableHeader>
          <div>User Requirements</div>
          <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((consolidatedMaterial, index) => {
          const info = consolidatedMaterial.parsedInfo;
          const hasAnyPurchased = consolidatedMaterial.consolidatedIds.some(id => purchasedMaterials.has(id));
          const allSelected = consolidatedMaterial.consolidatedIds.every(id => selectedMaterials.has(id));
          
          return (
            <div
              key={`consolidated-${index}`}
              style={{
                display: 'grid',
                gridTemplateColumns: '50px 200px 120px 150px 180px 200px 200px',
                gap: '16px',
                padding: '16px',
                borderBottom: index < filteredMaterials.length - 1 ? '1px solid #f1f5f9' : 'none',
                background: allSelected ? '#eff6ff' : (hasAnyPurchased ? '#fef3c7' : 'white'),
                transition: 'background 0.15s ease',
                textAlign: 'center'
              }}
              onMouseEnter={(e) => {
                if (!allSelected && !hasAnyPurchased) {
                  e.target.style.background = '#f8fafc';
                }
              }}
              onMouseLeave={(e) => {
                if (!allSelected && !hasAnyPurchased) {
                  e.target.style.background = 'white';
                }
              }}
            >
              <div>
                <input
                  type="checkbox"
                  checked={allSelected}
                  onChange={() => handleMaterialSelect(consolidatedMaterial)}
                  disabled={hasAnyPurchased}
                  style={{ 
                    cursor: hasAnyPurchased ? 'not-allowed' : 'pointer',
                    opacity: hasAnyPurchased ? 0.5 : 1
                  }}
                />
              </div>
              <div style={{ fontSize: '14px', color: '#1f2937', fontWeight: '500' }}>
                {info.type}
                {hasAnyPurchased && (
                  <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.grade}</div>
              <div style={{ fontSize: '14px', color: '#1f2937' }}>{info.userRequirements}</div>
              <div style={{ display: 'flex', gap: '4px', alignItems: 'center' }}>
                {!editingRequest[consolidatedMaterial.id] && savedRequests[consolidatedMaterial.id] ? (
                  // 저장된 상태 - 요구사항 표시 + 수정 버튼
                  <>
                    <div style={{
                      flex: 1,
                      padding: '8px',
                      border: '1px solid #e5e7eb',
                      borderRadius: '4px',
                      fontSize: '12px',
                      textAlign: 'center',
                      background: '#f9fafb',
                      color: '#374151'
                    }}>
                      {savedRequests[consolidatedMaterial.id]}
                    </div>
                    <button
                      onClick={() => handleEditRequest(consolidatedMaterial.id, savedRequests[consolidatedMaterial.id])}
                      disabled={hasAnyPurchased}
                      style={{
                        padding: '6px 8px',
                        border: 'none',
                        borderRadius: '4px',
                        background: hasAnyPurchased ? '#d1d5db' : '#f59e0b',
                        color: 'white',
                        fontSize: '10px',
                        cursor: hasAnyPurchased ? 'not-allowed' : 'pointer',
                        opacity: hasAnyPurchased ? 0.5 : 1,
                        minWidth: '40px'
                      }}
                    >
                      Edit
                    </button>
                  </>
                ) : (
                  // 편집 상태 - 입력 필드 + 저장 버튼
                  <>
                    <input
                      type="text"
                      value={userRequirements[consolidatedMaterial.id] || ''}
                      onChange={(e) => setUserRequirements({
                        ...userRequirements,
                        [consolidatedMaterial.id]: e.target.value
                      })}
                      placeholder="Enter additional request..."
                      disabled={hasAnyPurchased}
                      style={{
                        flex: 1,
                        padding: '8px',
                        border: '1px solid #d1d5db',
                        borderRadius: '4px',
                        fontSize: '12px',
                        opacity: hasAnyPurchased ? 0.5 : 1,
                        cursor: hasAnyPurchased ? 'not-allowed' : 'text'
                      }}
                    />
                    <button
                      onClick={() => handleSaveRequest(consolidatedMaterial.id, userRequirements[consolidatedMaterial.id] || '')}
                      disabled={hasAnyPurchased || savingRequest[consolidatedMaterial.id]}
                      style={{
                        padding: '6px 8px',
                        border: 'none',
                        borderRadius: '4px',
                        background: hasAnyPurchased ? '#d1d5db' : '#10b981',
                        color: 'white',
                        fontSize: '10px',
                        cursor: hasAnyPurchased || savingRequest[consolidatedMaterial.id] ? 'not-allowed' : 'pointer',
                        opacity: hasAnyPurchased ? 0.5 : 1,
                        minWidth: '40px'
                      }}
                    >
                      {savingRequest[consolidatedMaterial.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 Support Materials Found
          </div>
          <div style={{ fontSize: '14px' }}>
            {Object.keys(columnFilters).some(key => columnFilters[key]) 
              ? 'Try adjusting your filters' 
              : 'No support materials available in this BOM'}
          </div>
        </div>
      )}
    </div>
  );
};

export default SupportMaterialsView;
