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

const SpecialMaterialsView = ({ 
  materials, 
  selectedMaterials, 
  setSelectedMaterials,
  userRequirements,
  setUserRequirements,
  purchasedMaterials,
  onPurchasedMaterialsUpdate,
  updateMaterial, // 자재 업데이트 함수
  jobNo,
  fileId,
  user,
  onNavigate
}) => {
  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 || '' }));
  };

  // SPECIAL 자재 정보 파싱
  const parseSpecialInfo = (material) => {
    const description = material.original_description || '';
    const qty = Math.round(material.quantity || 0);
    
    // Type 추출 (큰 범주: 우선순위 기반 분류)
    let type = 'SPECIAL';
    const descUpper = description.toUpperCase();
    
    // 우선순위 1: 주요 장비 타입 (OIL PUMP, COMPRESSOR 등이 FLG보다 우선)
    if (descUpper.includes('OIL PUMP') || (descUpper.includes('PUMP') && !descUpper.includes('FITTING'))) {
      type = 'OIL PUMP';
    } else if (descUpper.includes('COMPRESSOR')) {
      type = 'COMPRESSOR';
    } else if (descUpper.includes('VALVE') && !descUpper.includes('FLG')) {
      type = 'VALVE';
    } 
    // 우선순위 2: 구조물/부품 타입
    else if (descUpper.includes('FLG') || descUpper.includes('FLANGE')) {
      // FLG가 있어도 주요 장비가 함께 있으면 장비 타입 우선
      if (descUpper.includes('OIL PUMP') || descUpper.includes('COMPRESSOR')) {
        if (descUpper.includes('OIL PUMP')) {
          type = 'OIL PUMP';
        } else if (descUpper.includes('COMPRESSOR')) {
          type = 'COMPRESSOR';
        }
      } else {
        type = 'FLANGE';
      }
    } else if (descUpper.includes('FITTING')) {
      type = 'FITTING';
    } else if (descUpper.includes('PIPE')) {
      type = 'PIPE';
    }
    
    // 도면 정보 (drawing_name 또는 line_no에서 추출)
    const drawing = material.drawing_name || material.line_no || '-';
    
    // 설명을 항목별로 분리 (콤마, 세미콜론, 파이프 등으로 구분)
    const parts = description
      .split(/[,;|\/]/)
      .map(part => part.trim())
      .filter(part => part.length > 0);
    
    // 최대 4개 항목으로 제한
    const detail1 = parts[0] || '-';
    const detail2 = parts[1] || '-';
    const detail3 = parts[2] || '-';
    const detail4 = parts[3] || '-';
    
    return {
      type,
      drawing,
      detail1,
      detail2,
      detail3,
      detail4,
      quantity: qty,
      originalQuantity: qty,
      purchaseQuantity: qty,
      isSpecial: 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 => {
      const info = parseSpecialInfo(material);
      
      // 컬럼 필터 적용
      for (const [key, filterValue] of Object.entries(columnFilters)) {
        if (filterValue && filterValue.trim()) {
          const materialValue = String(info[key] || '').toLowerCase();
          const filter = filterValue.toLowerCase();
          if (!materialValue.includes(filter)) {
            return false;
          }
        }
      }
      return true;
    });

    // 정렬 적용
    if (sortConfig.key) {
      filtered.sort((a, b) => {
        const aInfo = parseSpecialInfo(a);
        const bInfo = parseSpecialInfo(b);
        
        const aValue = aInfo[sortConfig.key];
        const bValue = bInfo[sortConfig.key];
        
        if (aValue < bValue) return sortConfig.direction === 'asc' ? -1 : 1;
        if (aValue > bValue) return sortConfig.direction === 'asc' ? 1 : -1;
        return 0;
      });
    }

    return filtered;
  };

  const filteredMaterials = getFilteredAndSortedMaterials();

  // 전체 선택/해제
  const handleSelectAll = () => {
    const selectableMaterials = filteredMaterials.filter(material => 
      !purchasedMaterials.has(material.id)
    );
    
    const allSelected = selectableMaterials.every(material => 
      selectedMaterials.has(material.id)
    );
    
    if (allSelected) {
      // 전체 해제
      const newSelected = new Set(selectedMaterials);
      selectableMaterials.forEach(material => {
        newSelected.delete(material.id);
      });
      setSelectedMaterials(newSelected);
    } else {
      // 전체 선택
      const newSelected = new Set(selectedMaterials);
      selectableMaterials.forEach(material => {
        newSelected.add(material.id);
      });
      setSelectedMaterials(newSelected);
    }
  };

  // 개별 선택/해제
  const handleMaterialSelect = (materialId) => {
    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 = `SPECIAL_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: 'SPECIAL',
        filename: excelFileName,
        user: user?.username || 'unknown'
      });
      
      // 2. 구매신청 생성
      console.log('📝 구매신청 생성 중...');
      const purchaseResponse = await api.post('/purchase-request/create', {
        materials_data: dataWithRequirements,
        file_id: fileId,
        job_no: jobNo
      });
      
      console.log('✅ 구매신청 생성 완료:', purchaseResponse.data);
      
      // 3. 엑셀 파일을 서버에 업로드
      console.log('📤 엑셀 파일 서버 업로드 중...');
      const formData = new FormData();
      formData.append('excel_file', excelBlob, excelFileName);
      formData.append('request_id', purchaseResponse.data.request_id);
      formData.append('filename', excelFileName);
      
      const uploadResponse = await api.post('/purchase-request/upload-excel', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });
      
      console.log('✅ 엑셀 업로드 완료:', uploadResponse.data);
      
      // 4. 구매신청된 자재들을 비활성화
      const purchasedIds = selectedMaterialsData.map(m => m.id);
      onPurchasedMaterialsUpdate(purchasedIds);
      
      // 5. 선택 해제
      setSelectedMaterials(new Set());
      
      // 6. 클라이언트에서도 다운로드
      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);
      
      console.log('✅ 스페셜 엑셀 내보내기 완료');
      alert(`스페셜 자재 엑셀 파일이 생성되었습니다.\n파일명: ${excelFileName}`);
      
      // 구매신청 관리 페이지로 이동
      if (onNavigate) {
        onNavigate('purchase-requests');
      }
      
    } catch (error) {
      console.error('❌ 스페셜 엑셀 내보내기 실패:', error);
      alert('엑셀 내보내기 중 오류가 발생했습니다: ' + (error.response?.data?.detail || error.message));
    }
  };

  const allSelected = filteredMaterials.length > 0 && 
    filteredMaterials.filter(material => !purchasedMaterials.has(material.id))
      .every(material => selectedMaterials.has(material.id));

  return (
    <div style={{ padding: '24px' }}>
      {/* 헤더 */}
      <div style={{
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
        marginBottom: '24px',
        padding: '20px',
        background: 'linear-gradient(135deg, #ec4899 0%, #be185d 100%)',
        borderRadius: '12px',
        color: 'white'
      }}>
        <div>
          <h2 style={{ margin: 0, fontSize: '24px', fontWeight: '700' }}>
            Special Items
          </h2>
          <p style={{ margin: '8px 0 0 0', opacity: 0.9 }}>
            특수 제작 품목 관리 ({filteredMaterials.length}개)
          </p>
        </div>
        <button
          onClick={handleExportToExcel}
          disabled={selectedMaterials.size === 0}
          style={{
            padding: '12px 24px',
            background: selectedMaterials.size > 0 ? 'rgba(255,255,255,0.2)' : 'rgba(255,255,255,0.1)',
            border: '1px solid rgba(255,255,255,0.3)',
            borderRadius: '8px',
            color: 'white',
            fontWeight: '600',
            cursor: selectedMaterials.size > 0 ? 'pointer' : 'not-allowed',
            transition: 'all 0.2s ease',
            backdropFilter: 'blur(10px)'
          }}
        >
          구매신청 ({selectedMaterials.size})
        </button>
      </div>

      {/* 테이블 */}
      <div style={{
        background: 'white',
        borderRadius: '12px',
        overflow: 'auto',
        maxHeight: '600px',
        border: '1px solid #e5e7eb',
        minWidth: '1400px'
      }}>
        <div style={{ minWidth: '1400px' }}>
          {/* 헤더 */}
          <div style={{
            display: 'grid',
            gridTemplateColumns: '50px 150px 200px 200px 200px 200px 200px 250px 150px',
            gap: '16px',
            padding: '16px',
            background: '#f8fafc',
            borderBottom: '2px solid #e2e8f0',
            fontWeight: '600',
            fontSize: '14px',
            color: '#1f2937',
            textAlign: 'center'
          }}>
            <div>
              <input
                type="checkbox"
                checked={allSelected}
                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="drawing" 
              filterKey="drawing"
              sortConfig={sortConfig}
              onSort={handleSort}
              columnFilters={columnFilters}
              onFilterChange={setColumnFilters}
              showFilterDropdown={showFilterDropdown}
              setShowFilterDropdown={setShowFilterDropdown}
            >
              Drawing
            </FilterableHeader>
            <FilterableHeader 
              sortKey="detail1" 
              filterKey="detail1"
              sortConfig={sortConfig}
              onSort={handleSort}
              columnFilters={columnFilters}
              onFilterChange={setColumnFilters}
              showFilterDropdown={showFilterDropdown}
              setShowFilterDropdown={setShowFilterDropdown}
            >
              Detail 1
            </FilterableHeader>
            <FilterableHeader 
              sortKey="detail2" 
              filterKey="detail2"
              sortConfig={sortConfig}
              onSort={handleSort}
              columnFilters={columnFilters}
              onFilterChange={setColumnFilters}
              showFilterDropdown={showFilterDropdown}
              setShowFilterDropdown={setShowFilterDropdown}
            >
              Detail 2
            </FilterableHeader>
            <FilterableHeader 
              sortKey="detail3" 
              filterKey="detail3"
              sortConfig={sortConfig}
              onSort={handleSort}
              columnFilters={columnFilters}
              onFilterChange={setColumnFilters}
              showFilterDropdown={showFilterDropdown}
              setShowFilterDropdown={setShowFilterDropdown}
            >
              Detail 3
            </FilterableHeader>
            <FilterableHeader 
              sortKey="detail4" 
              filterKey="detail4"
              sortConfig={sortConfig}
              onSort={handleSort}
              columnFilters={columnFilters}
              onFilterChange={setColumnFilters}
              showFilterDropdown={showFilterDropdown}
              setShowFilterDropdown={setShowFilterDropdown}
            >
              Detail 4
            </FilterableHeader>
            <div>Additional Request</div>
            <div>Purchase Quantity</div>
          </div>

          {/* 데이터 행들 */}
          <div>
            {filteredMaterials.map((material, index) => {
              const info = parseSpecialInfo(material);
              const isSelected = selectedMaterials.has(material.id);
              const isPurchased = purchasedMaterials.has(material.id);
              
              return (
                <div
                  key={material.id}
                  style={{
                    display: 'grid',
                    gridTemplateColumns: '50px 150px 200px 200px 200px 200px 200px 250px 150px',
                    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: '600'
                      }}>
                        PURCHASED
                      </span>
                    )}
                  </div>
                  <div style={{ fontSize: '14px', color: '#1f2937' }}>{info.drawing}</div>
                  <div style={{ fontSize: '14px', color: '#1f2937' }}>{info.detail1}</div>
                  <div style={{ fontSize: '14px', color: '#1f2937' }}>{info.detail2}</div>
                  <div style={{ fontSize: '14px', color: '#1f2937' }}>{info.detail3}</div>
                  <div style={{ fontSize: '14px', color: '#1f2937' }}>{info.detail4}</div>
                  <div style={{ display: 'flex', gap: '4px', alignItems: 'center' }}>
                    {!editingRequest[material.id] && savedRequests[material.id] ? (
                      // 저장된 상태 - 요구사항 표시 + 수정 버튼
                      <>
                        <div style={{
                          flex: 1,
                          padding: '6px 8px',
                          border: '1px solid #e5e7eb',
                          borderRadius: '4px',
                          fontSize: '12px',
                          textAlign: 'center',
                          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 8px',
                            border: '1px solid #d1d5db',
                            borderRadius: '4px',
                            fontSize: '12px',
                            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', textAlign: 'center' }}>
                    {info.purchaseQuantity}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {filteredMaterials.length === 0 && (
        <div style={{
          textAlign: 'center',
          padding: '60px 20px',
          color: '#6b7280',
          background: 'white',
          borderRadius: '12px',
          border: '1px solid #e5e7eb',
          marginTop: '20px'
        }}>
          <div style={{ fontSize: '48px', marginBottom: '16px' }}>📋</div>
          <h3 style={{ margin: '0 0 8px 0', color: '#374151' }}>스페셜 자재가 없습니다</h3>
          <p style={{ margin: 0 }}>특수 제작이 필요한 자재가 발견되면 여기에 표시됩니다.</p>
        </div>
      )}
    </div>
  );
};

export default SpecialMaterialsView;
