import React, { useState, useMemo } from 'react';
import { useRevisionComparison, useRevisionFiltering } from '../../hooks/useRevisionComparison';
import RevisionStatusIndicator, { RevisionChangeSummary } from './RevisionStatusIndicator';
import { LoadingSpinner, ErrorMessage } from '../common';
import './RevisionComparisonView.css';

/**
 * 리비전 비교 뷰 컴포넌트
 */
const RevisionComparisonView = ({ 
    currentFileId, 
    previousFileId, 
    category = null,
    onMaterialSelect = null,
    className = '' 
}) => {
    const [selectedTab, setSelectedTab] = useState('summary');
    const [expandedItems, setExpandedItems] = useState(new Set());

    const {
        comparisonResult,
        loading,
        error,
        compareRevisions,
        getComparisonSummary,
        getChangesByType,
        exportComparisonReport
    } = useRevisionComparison();

    const {
        filters,
        updateFilter,
        getFilteredChanges,
        getFilterSummary,
        resetFilters
    } = useRevisionFiltering(comparisonResult);

    // 초기 비교 실행
    React.useEffect(() => {
        if (currentFileId && previousFileId) {
            compareRevisions(currentFileId, previousFileId, category);
        }
    }, [currentFileId, previousFileId, category, compareRevisions]);

    const summary = useMemo(() => {
        return getComparisonSummary(comparisonResult);
    }, [comparisonResult, getComparisonSummary]);

    const filteredChanges = useMemo(() => {
        return getFilteredChanges();
    }, [getFilteredChanges]);

    const filteredSummary = useMemo(() => {
        return getFilterSummary();
    }, [getFilterSummary]);

    const toggleItemExpansion = (itemId) => {
        setExpandedItems(prev => {
            const newSet = new Set(prev);
            if (newSet.has(itemId)) {
                newSet.delete(itemId);
            } else {
                newSet.add(itemId);
            }
            return newSet;
        });
    };

    const handleExport = async (format) => {
        await exportComparisonReport(comparisonResult, format);
    };

    if (loading) {
        return (
            <div className="revision-comparison-loading">
                <LoadingSpinner />
                <p>리비전을 비교하고 있습니다...</p>
            </div>
        );
    }

    if (error) {
        return <ErrorMessage message={error} />;
    }

    if (!comparisonResult) {
        return (
            <div className="revision-comparison-empty">
                <p>비교할 리비전을 선택해주세요.</p>
            </div>
        );
    }

    return (
        <div className={`revision-comparison-view ${className}`}>
            {/* 헤더 */}
            <div className="comparison-header">
                <div className="header-info">
                    <h3>리비전 비교 결과</h3>
                    <p>
                        {category ? `${category} 카테고리` : '전체'} 자재 비교
                        {comparisonResult.comparison_date && (
                            <span className="comparison-date">
                                ({new Date(comparisonResult.comparison_date).toLocaleString()})
                            </span>
                        )}
                    </p>
                </div>
                
                <div className="header-actions">
                    <button 
                        className="btn-export"
                        onClick={() => handleExport('excel')}
                        disabled={loading}
                    >
                        📊 Excel 내보내기
                    </button>
                    <button 
                        className="btn-refresh"
                        onClick={() => compareRevisions(currentFileId, previousFileId, category)}
                        disabled={loading}
                    >
                        🔄 새로고침
                    </button>
                </div>
            </div>

            {/* 요약 카드 */}
            {summary && (
                <RevisionChangeSummary 
                    changes={comparisonResult.changes}
                    className="comparison-summary-card"
                />
            )}

            {/* 필터 섹션 */}
            <div className="comparison-filters">
                <div className="filter-group">
                    <label>변경 타입:</label>
                    <select 
                        value={filters.changeType} 
                        onChange={(e) => updateFilter('changeType', e.target.value)}
                    >
                        <option value="all">전체</option>
                        <option value="added">추가됨</option>
                        <option value="modified">수정됨</option>
                        <option value="removed">제거됨</option>
                        <option value="unchanged">변경없음</option>
                    </select>
                </div>

                {!category && (
                    <div className="filter-group">
                        <label>카테고리:</label>
                        <select 
                            value={filters.category} 
                            onChange={(e) => updateFilter('category', e.target.value)}
                        >
                            <option value="all">전체</option>
                            <option value="FITTING">FITTING</option>
                            <option value="FLANGE">FLANGE</option>
                            <option value="VALVE">VALVE</option>
                            <option value="GASKET">GASKET</option>
                            <option value="BOLT">BOLT</option>
                            <option value="SUPPORT">SUPPORT</option>
                            <option value="SPECIAL">SPECIAL</option>
                        </select>
                    </div>
                )}

                <div className="filter-group">
                    <label>검색:</label>
                    <input 
                        type="text"
                        placeholder="자재명 검색..."
                        value={filters.searchTerm}
                        onChange={(e) => updateFilter('searchTerm', e.target.value)}
                    />
                </div>

                <div className="filter-group">
                    <label>
                        <input 
                            type="checkbox"
                            checked={filters.showOnlySignificant}
                            onChange={(e) => updateFilter('showOnlySignificant', e.target.checked)}
                        />
                        중요한 변경사항만
                    </label>
                </div>

                <button className="btn-reset-filters" onClick={resetFilters}>
                    필터 초기화
                </button>
            </div>

            {/* 필터링된 요약 */}
            {filteredSummary && (
                <div className="filtered-summary">
                    <span>필터 결과: 총 {filteredSummary.total}개</span>
                    {filteredSummary.total !== summary?.totalChanges && (
                        <span className="filter-note">
                            (전체 {summary.totalChanges}개 중)
                        </span>
                    )}
                </div>
            )}

            {/* 탭 네비게이션 */}
            <div className="comparison-tabs">
                <button 
                    className={`tab-button ${selectedTab === 'summary' ? 'active' : ''}`}
                    onClick={() => setSelectedTab('summary')}
                >
                    요약
                </button>
                <button 
                    className={`tab-button ${selectedTab === 'details' ? 'active' : ''}`}
                    onClick={() => setSelectedTab('details')}
                >
                    상세 변경사항
                </button>
                <button 
                    className={`tab-button ${selectedTab === 'materials' ? 'active' : ''}`}
                    onClick={() => setSelectedTab('materials')}
                >
                    자재별 보기
                </button>
            </div>

            {/* 탭 콘텐츠 */}
            <div className="comparison-content">
                {selectedTab === 'summary' && (
                    <ComparisonSummaryTab 
                        summary={summary}
                        filteredChanges={filteredChanges}
                    />
                )}
                
                {selectedTab === 'details' && (
                    <ComparisonDetailsTab 
                        changes={filteredChanges || comparisonResult.changes}
                        expandedItems={expandedItems}
                        onToggleExpansion={toggleItemExpansion}
                        onMaterialSelect={onMaterialSelect}
                    />
                )}
                
                {selectedTab === 'materials' && (
                    <ComparisonMaterialsTab 
                        changes={filteredChanges || comparisonResult.changes}
                        onMaterialSelect={onMaterialSelect}
                    />
                )}
            </div>
        </div>
    );
};

/**
 * 요약 탭 컴포넌트
 */
const ComparisonSummaryTab = ({ summary, filteredChanges }) => {
    if (!summary) return null;

    const getChangeTypeStats = () => {
        if (!filteredChanges) return null;

        return Object.entries(filteredChanges).map(([changeType, items]) => ({
            type: changeType,
            count: items.length,
            items: items.slice(0, 5) // 상위 5개만 표시
        }));
    };

    const changeStats = getChangeTypeStats();

    return (
        <div className="comparison-summary-tab">
            <div className="summary-stats">
                <div className="stat-card">
                    <h4>전체 변경률</h4>
                    <div className="stat-value">
                        {summary.changePercentage?.toFixed(1)}%
                    </div>
                </div>
                
                <div className="stat-card">
                    <h4>안정성</h4>
                    <div className="stat-value">
                        {(100 - (summary.changePercentage || 0)).toFixed(1)}%
                    </div>
                </div>
                
                <div className="stat-card">
                    <h4>총 변경사항</h4>
                    <div className="stat-value">
                        {summary.totalChanges}개
                    </div>
                </div>
            </div>

            {changeStats && (
                <div className="change-previews">
                    {changeStats.map(stat => (
                        stat.count > 0 && (
                            <div key={stat.type} className="change-preview">
                                <h4>
                                    {getChangeTypeLabel(stat.type)} ({stat.count}개)
                                </h4>
                                <div className="preview-items">
                                    {stat.items.map((item, idx) => (
                                        <div key={idx} className="preview-item">
                                            <span className="material-desc">
                                                {getMaterialDescription(item)}
                                            </span>
                                            <RevisionStatusIndicator 
                                                status={getStatusFromChangeType(stat.type)}
                                                size="small"
                                            />
                                        </div>
                                    ))}
                                    {stat.count > 5 && (
                                        <div className="preview-more">
                                            외 {stat.count - 5}개 더...
                                        </div>
                                    )}
                                </div>
                            </div>
                        )
                    ))}
                </div>
            )}
        </div>
    );
};

/**
 * 상세 변경사항 탭 컴포넌트
 */
const ComparisonDetailsTab = ({ 
    changes, 
    expandedItems, 
    onToggleExpansion, 
    onMaterialSelect 
}) => {
    if (!changes) return null;

    return (
        <div className="comparison-details-tab">
            {Object.entries(changes).map(([changeType, items]) => (
                items.length > 0 && (
                    <div key={changeType} className="change-type-section">
                        <h4 className="change-type-header">
                            {getChangeTypeLabel(changeType)} ({items.length}개)
                        </h4>
                        
                        <div className="change-items">
                            {items.map((item, idx) => {
                                const itemId = `${changeType}-${idx}`;
                                const isExpanded = expandedItems.has(itemId);
                                
                                return (
                                    <div key={idx} className="change-item-card">
                                        <div 
                                            className="change-item-header"
                                            onClick={() => onToggleExpansion(itemId)}
                                        >
                                            <div className="item-info">
                                                <span className="material-desc">
                                                    {getMaterialDescription(item)}
                                                </span>
                                                <RevisionStatusIndicator 
                                                    status={getStatusFromChangeType(changeType)}
                                                    size="small"
                                                />
                                            </div>
                                            
                                            <div className="item-actions">
                                                {onMaterialSelect && (
                                                    <button 
                                                        className="btn-select"
                                                        onClick={(e) => {
                                                            e.stopPropagation();
                                                            onMaterialSelect(item);
                                                        }}
                                                    >
                                                        선택
                                                    </button>
                                                )}
                                                <span className="expand-icon">
                                                    {isExpanded ? '▼' : '▶'}
                                                </span>
                                            </div>
                                        </div>
                                        
                                        {isExpanded && (
                                            <div className="change-item-details">
                                                <MaterialChangeDetails 
                                                    item={item} 
                                                    changeType={changeType}
                                                />
                                            </div>
                                        )}
                                    </div>
                                );
                            })}
                        </div>
                    </div>
                )
            ))}
        </div>
    );
};

/**
 * 자재별 보기 탭 컴포넌트
 */
const ComparisonMaterialsTab = ({ changes, onMaterialSelect }) => {
    if (!changes) return null;

    // 모든 자재를 하나의 리스트로 통합
    const allMaterials = [];
    Object.entries(changes).forEach(([changeType, items]) => {
        items.forEach(item => {
            allMaterials.push({
                ...item,
                changeType
            });
        });
    });

    // 자재명으로 정렬
    allMaterials.sort((a, b) => {
        const descA = getMaterialDescription(a);
        const descB = getMaterialDescription(b);
        return descA.localeCompare(descB);
    });

    return (
        <div className="comparison-materials-tab">
            <div className="materials-table">
                <div className="table-header">
                    <span>자재명</span>
                    <span>카테고리</span>
                    <span>변경 타입</span>
                    <span>수량 변화</span>
                    <span>액션</span>
                </div>
                
                <div className="table-body">
                    {allMaterials.map((item, idx) => (
                        <div key={idx} className="table-row">
                            <span className="material-desc">
                                {getMaterialDescription(item)}
                            </span>
                            <span className="material-category">
                                {getMaterialCategory(item)}
                            </span>
                            <span className="change-type">
                                <RevisionStatusIndicator 
                                    status={getStatusFromChangeType(item.changeType)}
                                    size="small"
                                />
                            </span>
                            <span className="quantity-change">
                                {getQuantityChangeText(item)}
                            </span>
                            <span className="actions">
                                {onMaterialSelect && (
                                    <button 
                                        className="btn-select-small"
                                        onClick={() => onMaterialSelect(item)}
                                    >
                                        선택
                                    </button>
                                )}
                            </span>
                        </div>
                    ))}
                </div>
            </div>
        </div>
    );
};

/**
 * 자재 변경 상세 정보 컴포넌트
 */
const MaterialChangeDetails = ({ item, changeType }) => {
    const material = item.material || item.current || item.previous;
    const changes = item.changes || {};

    return (
        <div className="material-change-details">
            <div className="detail-grid">
                <div className="detail-section">
                    <h5>기본 정보</h5>
                    <div className="detail-items">
                        <div className="detail-item">
                            <span className="label">자재명:</span>
                            <span className="value">{material?.original_description}</span>
                        </div>
                        <div className="detail-item">
                            <span className="label">카테고리:</span>
                            <span className="value">{material?.classified_category}</span>
                        </div>
                        <div className="detail-item">
                            <span className="label">재질/규격:</span>
                            <span className="value">
                                {material?.material_grade} {material?.size_spec}
                            </span>
                        </div>
                    </div>
                </div>

                {Object.keys(changes).length > 0 && (
                    <div className="detail-section">
                        <h5>변경 내용</h5>
                        <div className="detail-items">
                            {Object.entries(changes).map(([field, change]) => (
                                <div key={field} className="detail-item">
                                    <span className="label">{getFieldLabel(field)}:</span>
                                    <span className="value change-value">
                                        {typeof change === 'object' ? (
                                            <>
                                                <span className="old-value">{change.previous}</span>
                                                <span className="arrow">→</span>
                                                <span className="new-value">{change.current}</span>
                                                {change.change && (
                                                    <span className="change-amount">
                                                        ({change.change > 0 ? '+' : ''}{change.change})
                                                    </span>
                                                )}
                                            </>
                                        ) : (
                                            change
                                        )}
                                    </span>
                                </div>
                            ))}
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
};

// 유틸리티 함수들
const getChangeTypeLabel = (changeType) => {
    const labels = {
        'added': '추가된 자재',
        'modified': '수정된 자재',
        'removed': '제거된 자재',
        'unchanged': '변경없는 자재'
    };
    return labels[changeType] || changeType;
};

const getStatusFromChangeType = (changeType) => {
    const statusMap = {
        'added': 'NEW',
        'modified': 'UPDATED',
        'removed': 'DELETED',
        'unchanged': 'COMPLETED'
    };
    return statusMap[changeType] || 'PENDING';
};

const getMaterialDescription = (item) => {
    const material = item.material || item.current || item.previous;
    return material?.original_description || '알 수 없는 자재';
};

const getMaterialCategory = (item) => {
    const material = item.material || item.current || item.previous;
    return material?.classified_category || 'UNKNOWN';
};

const getQuantityChangeText = (item) => {
    const changes = item.changes || {};
    const quantityChange = changes.quantity;
    
    if (!quantityChange) return '-';
    
    if (typeof quantityChange === 'object') {
        return `${quantityChange.previous} → ${quantityChange.current}`;
    }
    
    return quantityChange;
};

const getFieldLabel = (field) => {
    const labels = {
        'quantity': '수량',
        'material_grade': '재질',
        'schedule': 'Schedule',
        'size_spec': '규격',
        'main_nom': '주 호칭',
        'red_nom': '축소 호칭',
        'unit': '단위',
        'length': '길이'
    };
    return labels[field] || field;
};

export default RevisionComparisonView;
