import React, { useState, useEffect } from 'react';
import { useRevisionLogic } from '../../hooks/useRevisionLogic';
import { useRevisionStatus } from '../../hooks/useRevisionStatus';
import { LoadingSpinner, ErrorMessage } from '../../components/common';
import RevisionStatusIndicator from '../../components/revision/RevisionStatusIndicator';
import { FittingMaterialsView } from '../../components/bom';
import './CategoryRevisionPage.css';

const FittingRevisionPage = ({ 
    jobNo, 
    fileId, 
    previousFileId, 
    onNavigate, 
    user 
}) => {
    const [selectedMaterials, setSelectedMaterials] = useState(new Set());
    const [userRequirements, setUserRequirements] = useState({});
    const [purchasedMaterials, setPurchasedMaterials] = useState(new Set());

    // 리비전 로직 훅
    const {
        materials,
        loading: materialsLoading,
        error: materialsError,
        processingInfo,
        handleMaterialSelection,
        handleBulkAction,
        refreshMaterials
    } = useRevisionLogic(fileId, 'FITTING');

    // 리비전 상태 훅
    const {
        revisionStatus,
        loading: statusLoading,
        error: statusError,
        uploadNewRevision,
        navigateToRevision
    } = useRevisionStatus(jobNo, fileId);

    // 자재 업데이트 함수
    const updateMaterial = (materialId, updates) => {
        // 리비전 페이지에서는 자재 업데이트 로직을 별도로 처리
        console.log('Material update in revision page:', materialId, updates);
    };

    if (materialsLoading || statusLoading) {
        return <LoadingSpinner message="FITTING 리비전 데이터 로딩 중..." />;
    }

    const error = materialsError || statusError;
    if (error) {
        return <ErrorMessage message={error} onClose={() => window.location.reload()} />;
    }

    // FITTING 카테고리만 필터링
    const fittingMaterials = materials.filter(material => 
        material.classified_category === 'FITTING' || 
        material.category === 'FITTING'
    );

    // 기존 BOM 관리 페이지와 동일한 props 구성
    const commonProps = {
        materials: fittingMaterials,
        selectedMaterials,
        setSelectedMaterials,
        userRequirements,
        setUserRequirements,
        purchasedMaterials,
        onPurchasedMaterialsUpdate: (materialIds) => {
            setPurchasedMaterials(prev => {
                const newSet = new Set(prev);
                materialIds.forEach(id => newSet.add(id));
                return newSet;
            });
        },
        updateMaterial,
        fileId,
        jobNo,
        user,
        onNavigate
    };

    return (
        <div className="category-revision-page">
            {/* 헤더 */}
            <div className="materials-header">
                <div className="header-left">
                    <button 
                        className="back-button"
                        onClick={() => onNavigate('enhanced-revision')}
                    >
                        ← 리비전 관리로
                    </button>
                    <div className="header-center">
                        <h1>🔧 FITTING 리비전 관리</h1>
                        <span className="header-subtitle">
                            구매 상태를 고려한 FITTING 자재 리비전 처리
                        </span>
                    </div>
                </div>
                <div className="header-right">
                    <RevisionStatusIndicator 
                        revisionStatus={revisionStatus}
                        onUploadRevision={uploadNewRevision}
                        onNavigateToRevision={navigateToRevision}
                    />
                </div>
            </div>

            {/* 리비전 처리 상태 요약 */}
            {processingInfo && (
                <div className="revision-summary">
                    <h3>📊 리비전 처리 현황</h3>
                    <div className="summary-stats">
                        <div className="stat-item">
                            <span className="stat-label">전체 자재</span>
                            <span className="stat-value">{processingInfo.total_materials || 0}개</span>
                        </div>
                        <div className="stat-item revision">
                            <span className="stat-label">리비전 자재</span>
                            <span className="stat-value">{processingInfo.by_status?.REVISION_MATERIAL || 0}개</span>
                        </div>
                        <div className="stat-item inventory">
                            <span className="stat-label">재고 자재</span>
                            <span className="stat-value">{processingInfo.by_status?.INVENTORY_MATERIAL || 0}개</span>
                        </div>
                        <div className="stat-item deleted">
                            <span className="stat-label">삭제 자재</span>
                            <span className="stat-value">{processingInfo.by_status?.DELETED_MATERIAL || 0}개</span>
                        </div>
                    </div>
                </div>
            )}

            {/* 기존 FITTING 자재 뷰 컴포넌트 사용 */}
            <FittingMaterialsView {...commonProps} />
        </div>
    );
};

export default FittingRevisionPage;
