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 SupportRevisionPage = ({ 
    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 [supportTypeFilter, setSupportTypeFilter] = useState('all');
    const [loadRatingFilter, setLoadRatingFilter] = useState('all');

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

    // 리비전 비교 훅
    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()) ||
                material.support_type?.toLowerCase().includes(searchTerm.toLowerCase());

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

            const matchesSupportType = supportTypeFilter === 'all' || 
                material.support_type === supportTypeFilter;

            const matchesLoadRating = loadRatingFilter === 'all' || 
                material.load_rating === loadRatingFilter;

            return matchesSearch && matchesStatus && matchesSupportType && matchesLoadRating;
        });

        // 정렬
        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, supportTypeFilter, loadRatingFilter, sortBy, sortOrder]);

    // 고유 값들 추출 (필터 옵션용)
    const uniqueValues = useMemo(() => {
        if (!materials) return { supportTypes: [], loadRatings: [] };

        const supportTypes = [...new Set(materials.map(m => m.support_type).filter(Boolean))];
        const loadRatings = [...new Set(materials.map(m => m.load_rating).filter(Boolean))];

        return { supportTypes, loadRatings };
    }, [materials]);

    // 초기 비교 수행
    useEffect(() => {
        if (fileId && previousFileId && !comparisonResult) {
            performComparison('SUPPORT');
        }
    }, [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 formatQuantity = (quantity) => {
        if (quantity === null || quantity === undefined) return '-';
        return Math.round(parseFloat(quantity) || 0).toString();
    };

    // SUPPORT 자재 설명 생성 (지지대 타입과 하중 정보 포함)
    const generateSupportDescription = (material) => {
        const parts = [];
        
        if (material.support_type) parts.push(material.support_type);
        if (material.pipe_size) parts.push(`${material.pipe_size}"`);
        if (material.load_rating) parts.push(`${material.load_rating} 등급`);
        if (material.material_grade) parts.push(material.material_grade);
        
        const baseDesc = material.description || material.item_name || 'SUPPORT';
        
        return parts.length > 0 ? `${baseDesc} (${parts.join(', ')})` : baseDesc;
    };

    // 치수 정보 표시
    const formatDimensions = (material) => {
        const dims = [];
        if (material.length_mm) dims.push(`L${material.length_mm}`);
        if (material.width_mm) dims.push(`W${material.width_mm}`);
        if (material.height_mm) dims.push(`H${material.height_mm}`);
        
        return dims.length > 0 ? dims.join('×') : '-';
    };

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

    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>🏗️ SUPPORT 리비전 관리</h1>
                        <span className="header-subtitle">
                            지지대 타입과 하중등급을 고려한 SUPPORT 자재 리비전 처리
                        </span>
                    </div>
                </div>
                <div className="header-right">
                    <RevisionStatusIndicator 
                        revisionStatus={revisionStatus}
                        onUploadRevision={uploadNewRevision}
                        onNavigateToRevision={navigateToRevision}
                    />
                </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={supportTypeFilter} onChange={(e) => setSupportTypeFilter(e.target.value)}>
                            <option value="all">전체</option>
                            {uniqueValues.supportTypes.map(type => (
                                <option key={type} value={type}>{type}</option>
                            ))}
                        </select>
                    </div>

                    <div className="control-group">
                        <label>하중등급:</label>
                        <select value={loadRatingFilter} onChange={(e) => setLoadRatingFilter(e.target.value)}>
                            <option value="all">전체</option>
                            {uniqueValues.loadRatings.map(rating => (
                                <option key={rating} value={rating}>{rating}</option>
                            ))}
                        </select>
                    </div>

                    <div className="control-group">
                        <label>정렬:</label>
                        <select value={sortBy} onChange={(e) => setSortBy(e.target.value)}>
                            <option value="description">자재명</option>
                            <option value="support_type">지지대 타입</option>
                            <option value="load_rating">하중등급</option>
                            <option value="pipe_size">파이프 크기</option>
                            <option value="quantity">수량</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>
                        </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 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)}`}
                        >
                            <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">{generateSupportDescription(material)}</div>
                                    {material.processing_info?.notes && (
                                        <div className="material-notes">{material.processing_info.notes}</div>
                                    )}
                                    {material.load_capacity && (
                                        <div className="material-capacity">💪 하중용량: {material.load_capacity}</div>
                                    )}
                                </div>
                            </div>
                            <div className="table-cell">{material.support_type || '-'}</div>
                            <div className="table-cell">{material.pipe_size ? `${material.pipe_size}"` : '-'}</div>
                            <div className="table-cell">{material.load_rating || '-'}</div>
                            <div className="table-cell">{formatDimensions(material)}</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-edit"
                                        onClick={() => {/* 편집 로직 */}}
                                        title="편집"
                                    >
                                        ✏️
                                    </button>
                                    <button 
                                        className="btn-small btn-calc"
                                        onClick={() => {/* 하중 계산 로직 */}}
                                        title="하중 계산"
                                    >
                                        🧮
                                    </button>
                                </div>
                            </div>
                        </div>
                    ))}
                </div>

                {filteredAndSortedMaterials.length === 0 && (
                    <div className="empty-state">
                        <p>조건에 맞는 SUPPORT 자재가 없습니다.</p>
                    </div>
                )}
            </div>

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

export default SupportRevisionPage;
