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

const UnclassifiedRevisionPage = ({ 
    jobNo, 
    fileId, 
    previousFileId, 
    onNavigate, 
    user 
}) => {
    const [selectedMaterials, setSelectedMaterials] = useState(new Set());
    const [showConfirmDialog, setShowConfirmDialog] = useState(false);
    const [actionType, setActionType] = useState('');
    const [searchTerm, setSearchTerm] = useState('');
    const [statusFilter, setStatusFilter] = useState('all');
    const [sortBy, setSortBy] = useState('description');
    const [sortOrder, setSortOrder] = useState('asc');
    const [classificationFilter, setClassificationFilter] = useState('all');
    const [showClassificationTools, setShowClassificationTools] = useState(false);

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

    // 리비전 비교 훅
    const {
        comparisonResult,
        loading: comparisonLoading,
        error: comparisonError,
        performComparison,
        getFilteredComparison
    } = useRevisionComparison(fileId, previousFileId);

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

    // 필터링 및 정렬된 자재 목록
    const filteredAndSortedMaterials = useMemo(() => {
        if (!materials) return [];

        let filtered = materials.filter(material => {
            const matchesSearch = !searchTerm || 
                material.description?.toLowerCase().includes(searchTerm.toLowerCase()) ||
                material.item_name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
                material.drawing_name?.toLowerCase().includes(searchTerm.toLowerCase());

            const matchesStatus = statusFilter === 'all' || 
                material.processing_info?.display_status === statusFilter;

            const matchesClassification = classificationFilter === 'all' || 
                (classificationFilter === 'needs_classification' && material.classification_confidence < 0.5) ||
                (classificationFilter === 'low_confidence' && material.classification_confidence >= 0.5 && material.classification_confidence < 0.8) ||
                (classificationFilter === 'high_confidence' && material.classification_confidence >= 0.8);

            return matchesSearch && matchesStatus && matchesClassification;
        });

        // 정렬
        filtered.sort((a, b) => {
            let aValue = a[sortBy] || '';
            let bValue = b[sortBy] || '';

            if (typeof aValue === 'string') {
                aValue = aValue.toLowerCase();
                bValue = bValue.toLowerCase();
            }

            if (sortOrder === 'asc') {
                return aValue < bValue ? -1 : aValue > bValue ? 1 : 0;
            } else {
                return aValue > bValue ? -1 : aValue < bValue ? 1 : 0;
            }
        });

        return filtered;
    }, [materials, searchTerm, statusFilter, classificationFilter, sortBy, sortOrder]);

    // 분류 신뢰도별 통계
    const classificationStats = useMemo(() => {
        if (!materials) return { needsClassification: 0, lowConfidence: 0, highConfidence: 0 };

        return materials.reduce((stats, material) => {
            const confidence = material.classification_confidence || 0;
            if (confidence < 0.5) stats.needsClassification++;
            else if (confidence < 0.8) stats.lowConfidence++;
            else stats.highConfidence++;
            return stats;
        }, { needsClassification: 0, lowConfidence: 0, highConfidence: 0 });
    }, [materials]);

    // 초기 비교 수행
    useEffect(() => {
        if (fileId && previousFileId && !comparisonResult) {
            performComparison('UNCLASSIFIED');
        }
    }, [fileId, previousFileId, comparisonResult, performComparison]);

    // 자재 선택 처리
    const handleMaterialSelect = (materialId, isSelected) => {
        const newSelected = new Set(selectedMaterials);
        if (isSelected) {
            newSelected.add(materialId);
        } else {
            newSelected.delete(materialId);
        }
        setSelectedMaterials(newSelected);
        handleMaterialSelection(materialId, isSelected);
    };

    // 전체 선택/해제
    const handleSelectAll = (isSelected) => {
        if (isSelected) {
            const allIds = new Set(filteredAndSortedMaterials.map(m => m.id));
            setSelectedMaterials(allIds);
            filteredAndSortedMaterials.forEach(m => handleMaterialSelection(m.id, true));
        } else {
            setSelectedMaterials(new Set());
            filteredAndSortedMaterials.forEach(m => handleMaterialSelection(m.id, false));
        }
    };

    // 액션 실행
    const executeAction = async (action) => {
        setActionType(action);
        setShowConfirmDialog(true);
    };

    const confirmAction = async () => {
        try {
            await handleBulkAction(actionType, Array.from(selectedMaterials));
            setSelectedMaterials(new Set());
            setShowConfirmDialog(false);
            await refreshMaterials();
        } catch (error) {
            console.error('Action failed:', error);
        }
    };

    // 상태별 색상 클래스
    const getStatusClass = (status) => {
        switch (status) {
            case 'REVISION_MATERIAL': return 'status-revision';
            case 'INVENTORY_MATERIAL': return 'status-inventory';
            case 'DELETED_MATERIAL': return 'status-deleted';
            case 'NEW_MATERIAL': return 'status-new';
            default: return 'status-normal';
        }
    };

    // 분류 신뢰도별 색상 클래스
    const getConfidenceClass = (confidence) => {
        if (confidence < 0.5) return 'confidence-low';
        if (confidence < 0.8) return 'confidence-medium';
        return 'confidence-high';
    };

    // 수량 표시 (정수로 변환)
    const formatQuantity = (quantity) => {
        if (quantity === null || quantity === undefined) return '-';
        return Math.round(parseFloat(quantity) || 0).toString();
    };

    // 분류 신뢰도 표시
    const formatConfidence = (confidence) => {
        if (confidence === null || confidence === undefined) return '0%';
        return `${Math.round(confidence * 100)}%`;
    };

    // 분류 제안 카테고리 표시
    const getSuggestedCategory = (material) => {
        // 간단한 키워드 기반 분류 제안
        const desc = (material.description || material.item_name || '').toLowerCase();
        
        if (desc.includes('pipe') || desc.includes('파이프')) return 'PIPE';
        if (desc.includes('flange') || desc.includes('플랜지')) return 'FLANGE';
        if (desc.includes('fitting') || desc.includes('피팅')) return 'FITTING';
        if (desc.includes('support') || desc.includes('지지대')) return 'SUPPORT';
        if (desc.includes('valve') || desc.includes('밸브')) return 'SPECIAL';
        
        return '수동 분류 필요';
    };

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

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

    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>❓ UNCLASSIFIED 리비전 관리</h1>
                        <span className="header-subtitle">
                            미분류 자재의 리비전 처리 및 분류 작업
                        </span>
                    </div>
                </div>
                <div className="header-right">
                    <RevisionStatusIndicator 
                        revisionStatus={revisionStatus}
                        onUploadRevision={uploadNewRevision}
                        onNavigateToRevision={navigateToRevision}
                    />
                </div>
            </div>

            {/* 분류 통계 카드 */}
            <div className="classification-stats-card">
                <div className="stats-header">
                    <h3>🔍 분류 현황</h3>
                    <button 
                        className="btn-toggle-tools"
                        onClick={() => setShowClassificationTools(!showClassificationTools)}
                    >
                        {showClassificationTools ? '도구 숨기기' : '분류 도구 보기'}
                    </button>
                </div>
                <div className="stats-grid">
                    <div className="stat-item needs-classification">
                        <div className="stat-value">{classificationStats.needsClassification}</div>
                        <div className="stat-label">분류 필요</div>
                    </div>
                    <div className="stat-item low-confidence">
                        <div className="stat-value">{classificationStats.lowConfidence}</div>
                        <div className="stat-label">낮은 신뢰도</div>
                    </div>
                    <div className="stat-item high-confidence">
                        <div className="stat-value">{classificationStats.highConfidence}</div>
                        <div className="stat-label">높은 신뢰도</div>
                    </div>
                </div>
            </div>

            {/* 컨트롤 섹션 */}
            <div className="control-section">
                <div className="section-header">
                    <h3>📊 자재 현황 및 필터</h3>
                    {processingInfo && (
                        <div className="processing-summary">
                            전체: {processingInfo.total_materials}개 | 
                            리비전: {processingInfo.by_status.REVISION_MATERIAL || 0}개 | 
                            재고: {processingInfo.by_status.INVENTORY_MATERIAL || 0}개 | 
                            삭제: {processingInfo.by_status.DELETED_MATERIAL || 0}개
                        </div>
                    )}
                </div>

                <div className="control-grid">
                    <div className="control-group">
                        <label>검색:</label>
                        <input
                            type="text"
                            placeholder="자재명, 도면명으로 검색..."
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                        />
                    </div>

                    <div className="control-group">
                        <label>상태 필터:</label>
                        <select value={statusFilter} onChange={(e) => setStatusFilter(e.target.value)}>
                            <option value="all">전체</option>
                            <option value="REVISION_MATERIAL">리비전 자재</option>
                            <option value="INVENTORY_MATERIAL">재고 자재</option>
                            <option value="DELETED_MATERIAL">삭제 자재</option>
                            <option value="NEW_MATERIAL">신규 자재</option>
                        </select>
                    </div>

                    <div className="control-group">
                        <label>분류 상태:</label>
                        <select value={classificationFilter} onChange={(e) => setClassificationFilter(e.target.value)}>
                            <option value="all">전체</option>
                            <option value="needs_classification">분류 필요 (&lt;50%)</option>
                            <option value="low_confidence">낮은 신뢰도 (50-80%)</option>
                            <option value="high_confidence">높은 신뢰도 (&gt;80%)</option>
                        </select>
                    </div>

                    <div className="control-group">
                        <label>정렬:</label>
                        <select value={sortBy} onChange={(e) => setSortBy(e.target.value)}>
                            <option value="description">자재명</option>
                            <option value="classification_confidence">분류 신뢰도</option>
                            <option value="quantity">수량</option>
                            <option value="drawing_name">도면명</option>
                        </select>
                        <select value={sortOrder} onChange={(e) => setSortOrder(e.target.value)}>
                            <option value="asc">오름차순</option>
                            <option value="desc">내림차순</option>
                        </select>
                    </div>
                </div>

                {/* 선택된 자재 액션 */}
                {selectedMaterials.size > 0 && (
                    <div className="selected-actions">
                        <span className="selected-count">
                            {selectedMaterials.size}개 선택됨
                        </span>
                        <div className="action-buttons">
                            <button 
                                className="btn-action btn-purchase"
                                onClick={() => executeAction('request_purchase')}
                            >
                                구매 신청
                            </button>
                            <button 
                                className="btn-action btn-inventory"
                                onClick={() => executeAction('mark_inventory')}
                            >
                                재고 처리
                            </button>
                            <button 
                                className="btn-action btn-delete"
                                onClick={() => executeAction('mark_deleted')}
                            >
                                삭제 처리
                            </button>
                            <button 
                                className="btn-action btn-classify"
                                onClick={() => executeAction('auto_classify')}
                                style={{ background: '#8b5cf6' }}
                            >
                                자동 분류
                            </button>
                        </div>
                    </div>
                )}
            </div>

            {/* 자재 테이블 */}
            <div className="materials-table-container">
                <div className="table-header">
                    <div className="header-cell checkbox-cell">
                        <input
                            type="checkbox"
                            checked={selectedMaterials.size === filteredAndSortedMaterials.length && filteredAndSortedMaterials.length > 0}
                            onChange={(e) => handleSelectAll(e.target.checked)}
                        />
                    </div>
                    <div className="header-cell">상태</div>
                    <div className="header-cell">자재명</div>
                    <div className="header-cell">분류 신뢰도</div>
                    <div className="header-cell">제안 카테고리</div>
                    <div className="header-cell">도면명</div>
                    <div className="header-cell">수량</div>
                    <div className="header-cell">단위</div>
                    <div className="header-cell">액션</div>
                </div>

                <div className="table-body">
                    {filteredAndSortedMaterials.map((material) => (
                        <div 
                            key={material.id} 
                            className={`table-row ${getStatusClass(material.processing_info?.display_status)} ${getConfidenceClass(material.classification_confidence)}`}
                        >
                            <div className="table-cell checkbox-cell">
                                <input
                                    type="checkbox"
                                    checked={selectedMaterials.has(material.id)}
                                    onChange={(e) => handleMaterialSelect(material.id, e.target.checked)}
                                />
                            </div>
                            <div className="table-cell">
                                <span className={`status-badge ${getStatusClass(material.processing_info?.display_status)}`}>
                                    {material.processing_info?.display_status || 'NORMAL'}
                                </span>
                            </div>
                            <div className="table-cell">
                                <div className="material-info">
                                    <div className="material-name">{material.description || material.item_name || '자재명 없음'}</div>
                                    {material.processing_info?.notes && (
                                        <div className="material-notes">{material.processing_info.notes}</div>
                                    )}
                                </div>
                            </div>
                            <div className="table-cell">
                                <span className={`confidence-badge ${getConfidenceClass(material.classification_confidence)}`}>
                                    {formatConfidence(material.classification_confidence)}
                                </span>
                            </div>
                            <div className="table-cell">
                                <span className="suggested-category">
                                    {getSuggestedCategory(material)}
                                </span>
                            </div>
                            <div className="table-cell">{material.drawing_name || '-'}</div>
                            <div className="table-cell quantity-cell">
                                <span className="quantity-value">
                                    {formatQuantity(material.quantity)}
                                </span>
                                {material.processing_info?.quantity_change && (
                                    <span className="quantity-change">
                                        ({material.processing_info.quantity_change > 0 ? '+' : ''}
                                        {formatQuantity(material.processing_info.quantity_change)})
                                    </span>
                                )}
                            </div>
                            <div className="table-cell">{material.unit || 'EA'}</div>
                            <div className="table-cell">
                                <div className="action-buttons-small">
                                    <button 
                                        className="btn-small btn-view"
                                        onClick={() => {/* 상세 보기 로직 */}}
                                        title="상세 정보"
                                    >
                                        👁️
                                    </button>
                                    <button 
                                        className="btn-small btn-classify"
                                        onClick={() => {/* 수동 분류 로직 */}}
                                        title="수동 분류"
                                    >
                                        🏷️
                                    </button>
                                    <button 
                                        className="btn-small btn-auto-classify"
                                        onClick={() => {/* 자동 분류 로직 */}}
                                        title="자동 분류"
                                    >
                                        🤖
                                    </button>
                                </div>
                            </div>
                        </div>
                    ))}
                </div>

                {filteredAndSortedMaterials.length === 0 && (
                    <div className="empty-state">
                        <p>조건에 맞는 UNCLASSIFIED 자재가 없습니다.</p>
                        {materials && materials.length === 0 && (
                            <p>🎉 모든 자재가 분류되었습니다!</p>
                        )}
                    </div>
                )}
            </div>

            {/* 확인 다이얼로그 */}
            {showConfirmDialog && (
                <ConfirmDialog
                    title="작업 확인"
                    message={`선택된 ${selectedMaterials.size}개 자재에 대해 "${actionType}" 작업을 수행하시겠습니까?`}
                    onConfirm={confirmAction}
                    onCancel={() => setShowConfirmDialog(false)}
                />
            )}
        </div>
    );
};

export default UnclassifiedRevisionPage;
