import React, { useState, useEffect } from 'react';
import { api } from '../api';
import { LoadingSpinner, ErrorMessage, ConfirmDialog } from '../components/common';
import FittingRevisionPage from './revision/FittingRevisionPage';
import FlangeRevisionPage from './revision/FlangeRevisionPage';
import SpecialRevisionPage from './revision/SpecialRevisionPage';
import SupportRevisionPage from './revision/SupportRevisionPage';
import UnclassifiedRevisionPage from './revision/UnclassifiedRevisionPage';
import ValveRevisionPage from './revision/ValveRevisionPage';
import GasketRevisionPage from './revision/GasketRevisionPage';
import BoltRevisionPage from './revision/BoltRevisionPage';
import PipeCuttingPlanPage from './revision/PipeCuttingPlanPage';
import './EnhancedRevisionPage.css';

const EnhancedRevisionPage = ({ onNavigate, user }) => {
    const [jobs, setJobs] = useState([]);
    const [selectedJob, setSelectedJob] = useState('');
    const [files, setFiles] = useState([]);
    const [currentFile, setCurrentFile] = useState('');
    const [previousFile, setPreviousFile] = useState('');
    const [comparisonResult, setComparisonResult] = useState(null);
    const [comparisonHistory, setComparisonHistory] = useState([]);
    const [pipeLengthSummary, setPipeLengthSummary] = useState(null);
    
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState('');
    const [showApplyDialog, setShowApplyDialog] = useState(false);
    const [selectedComparison, setSelectedComparison] = useState(null);
    
    // 카테고리별 페이지 라우팅
    const [selectedCategory, setSelectedCategory] = useState('');
    const [categoryMaterials, setCategoryMaterials] = useState({});

    // 작업 목록 조회
    useEffect(() => {
        fetchJobs();
    }, []);

    // 선택된 작업의 파일 목록 조회
    useEffect(() => {
        if (selectedJob) {
            fetchJobFiles();
            fetchComparisonHistory();
        }
    }, [selectedJob]);

    // 현재 파일의 PIPE 길이 요약 및 카테고리별 자재 조회
    useEffect(() => {
        if (currentFile) {
            fetchPipeLengthSummary();
            fetchCategoryMaterials();
        }
    }, [currentFile]);

    const fetchJobs = async () => {
        try {
            const response = await api.get('/dashboard/projects');
            setJobs(response.data.projects || []);
        } catch (err) {
            setError('작업 목록 조회 실패: ' + err.message);
        }
    };

    const fetchJobFiles = async () => {
        try {
            const response = await api.get(`/files/by-job/${selectedJob}`);
            setFiles(response.data || []);
        } catch (err) {
            setError('파일 목록 조회 실패: ' + err.message);
        }
    };

    const fetchComparisonHistory = async () => {
        try {
            const response = await api.get(`/enhanced-revision/comparison-history/${selectedJob}`);
            setComparisonHistory(response.data.data || []);
        } catch (err) {
            console.error('비교 이력 조회 실패:', err);
        }
    };

    const fetchPipeLengthSummary = async () => {
        try {
            const response = await api.get(`/enhanced-revision/pipe-length-summary/${currentFile}`);
            setPipeLengthSummary(response.data.data);
        } catch (err) {
            console.error('PIPE 길이 요약 조회 실패:', err);
        }
    };

    const fetchCategoryMaterials = async () => {
        if (!currentFile) return;

        try {
            const categories = ['PIPE', 'FITTING', 'FLANGE', 'VALVE', 'GASKET', 'BOLT', 'SUPPORT', 'SPECIAL', 'UNCLASSIFIED'];
            const materialStats = {};

            for (const category of categories) {
                try {
                    const response = await api.get(`/revision-material/category/${currentFile}/${category}`);
                    materialStats[category] = {
                        count: response.data.data?.materials?.length || 0,
                        processing_info: response.data.data?.processing_info || {}
                    };
                } catch (err) {
                    console.error(`Failed to fetch ${category} materials:`, err);
                    materialStats[category] = { count: 0, processing_info: {} };
                }
            }

            setCategoryMaterials(materialStats);
        } catch (err) {
            console.error('카테고리별 자재 조회 실패:', err);
        }
    };

    const handleCompareRevisions = async () => {
        if (!selectedJob || !currentFile) {
            setError('작업과 현재 파일을 선택해주세요.');
            return;
        }

        setLoading(true);
        setError('');

        try {
            const params = {
                job_no: selectedJob,
                current_file_id: parseInt(currentFile),
                save_comparison: true
            };

            if (previousFile) {
                params.previous_file_id = parseInt(previousFile);
            }

            const response = await api.post('/enhanced-revision/compare-revisions', null, { params });
            setComparisonResult(response.data.data);
            
            // 비교 이력 새로고침
            fetchComparisonHistory();
            
        } catch (err) {
            setError('리비전 비교 실패: ' + err.message);
        } finally {
            setLoading(false);
        }
    };

    const handleApplyChanges = async (comparisonId) => {
        setLoading(true);
        setError('');

        try {
            const response = await api.post(`/enhanced-revision/apply-revision-changes/${comparisonId}`);
            
            if (response.data.success) {
                alert('리비전 변경사항이 성공적으로 적용되었습니다.');
                fetchComparisonHistory();
                setComparisonResult(null);
            }
        } catch (err) {
            setError('변경사항 적용 실패: ' + err.message);
        } finally {
            setLoading(false);
            setShowApplyDialog(false);
        }
    };

    const handleRecalculatePipeLengths = async () => {
        if (!currentFile) return;

        setLoading(true);
        try {
            const response = await api.post(`/enhanced-revision/recalculate-pipe-lengths/${currentFile}`);
            
            if (response.data.success) {
                alert(`PIPE 자재 ${response.data.data.updated_count}개의 길이를 재계산했습니다.`);
                fetchPipeLengthSummary();
            }
        } catch (err) {
            setError('PIPE 길이 재계산 실패: ' + err.message);
        } finally {
            setLoading(false);
        }
    };

    const renderComparisonSummary = (summary) => {
        if (!summary) return null;

        return (
            <div className="comparison-summary">
                <h3>📊 비교 요약</h3>
                <div className="summary-grid">
                    <div className="summary-card purchased">
                        <h4>🛒 구매 완료 자재</h4>
                        <div className="summary-stats">
                            <span className="stat-item">유지: {summary.purchased_maintained}</span>
                            <span className="stat-item increase">추가구매: {summary.purchased_increased}</span>
                            <span className="stat-item decrease">잉여재고: {summary.purchased_decreased}</span>
                        </div>
                    </div>
                    <div className="summary-card unpurchased">
                        <h4>📋 구매 미완료 자재</h4>
                        <div className="summary-stats">
                            <span className="stat-item">유지: {summary.unpurchased_maintained}</span>
                            <span className="stat-item increase">수량증가: {summary.unpurchased_increased}</span>
                            <span className="stat-item decrease">수량감소: {summary.unpurchased_decreased}</span>
                        </div>
                    </div>
                    <div className="summary-card changes">
                        <h4>🔄 변경사항</h4>
                        <div className="summary-stats">
                            <span className="stat-item new">신규: {summary.new_materials}</span>
                            <span className="stat-item deleted">삭제: {summary.deleted_materials}</span>
                        </div>
                    </div>
                </div>
            </div>
        );
    };

    const renderChangeDetails = (changes) => {
        if (!changes) return null;

        return (
            <div className="change-details">
                <h3>📋 상세 변경사항</h3>
                
                {/* 구매 완료 자재 변경사항 */}
                {changes.purchased_materials && (
                    <div className="change-section">
                        <h4>🛒 구매 완료 자재</h4>
                        
                        {changes.purchased_materials.additional_purchase_needed?.length > 0 && (
                            <div className="change-category additional-purchase">
                                <h5>📈 추가 구매 필요</h5>
                                <div className="material-list">
                                    {changes.purchased_materials.additional_purchase_needed.map((item, idx) => (
                                        <div key={idx} className="material-item">
                                            <span className="material-desc">{item.material.original_description}</span>
                                            <span className="quantity-change">
                                                {item.previous_quantity} → {item.current_quantity} 
                                                (+{item.additional_needed})
                                            </span>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        )}

                        {changes.purchased_materials.excess_inventory?.length > 0 && (
                            <div className="change-category excess-inventory">
                                <h5>📉 잉여 재고</h5>
                                <div className="material-list">
                                    {changes.purchased_materials.excess_inventory.map((item, idx) => (
                                        <div key={idx} className="material-item">
                                            <span className="material-desc">{item.material.original_description}</span>
                                            <span className="quantity-change">
                                                {item.previous_quantity} → {item.current_quantity} 
                                                (-{item.excess_quantity})
                                            </span>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        )}
                    </div>
                )}

                {/* 구매 미완료 자재 변경사항 */}
                {changes.unpurchased_materials && (
                    <div className="change-section">
                        <h4>📋 구매 미완료 자재</h4>
                        
                        {changes.unpurchased_materials.quantity_updated?.length > 0 && (
                            <div className="change-category quantity-updated">
                                <h5>📊 수량 변경</h5>
                                <div className="material-list">
                                    {changes.unpurchased_materials.quantity_updated.map((item, idx) => (
                                        <div key={idx} className="material-item">
                                            <span className="material-desc">{item.material.original_description}</span>
                                            <span className="quantity-change">
                                                {item.previous_quantity} → {item.current_quantity}
                                            </span>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        )}

                        {changes.unpurchased_materials.quantity_reduced?.length > 0 && (
                            <div className="change-category quantity-reduced">
                                <h5>📉 수량 감소</h5>
                                <div className="material-list">
                                    {changes.unpurchased_materials.quantity_reduced.map((item, idx) => (
                                        <div key={idx} className="material-item">
                                            <span className="material-desc">{item.material.original_description}</span>
                                            <span className="quantity-change">
                                                {item.previous_quantity} → {item.current_quantity}
                                            </span>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        )}
                    </div>
                )}

                {/* 신규/삭제 자재 */}
                {(changes.new_materials?.length > 0 || changes.deleted_materials?.length > 0) && (
                    <div className="change-section">
                        <h4>🔄 신규/삭제 자재</h4>
                        
                        {changes.new_materials?.length > 0 && (
                            <div className="change-category new-materials">
                                <h5>✅ 신규 자재</h5>
                                <div className="material-list">
                                    {changes.new_materials.map((item, idx) => (
                                        <div key={idx} className="material-item">
                                            <span className="material-desc">{item.material.original_description}</span>
                                            <span className="quantity-info">수량: {item.material.quantity}</span>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        )}

                        {changes.deleted_materials?.length > 0 && (
                            <div className="change-category deleted-materials">
                                <h5>❌ 삭제된 자재</h5>
                                <div className="material-list">
                                    {changes.deleted_materials.map((item, idx) => (
                                        <div key={idx} className="material-item">
                                            <span className="material-desc">{item.material.original_description}</span>
                                            <span className="reason">{item.reason}</span>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        )}
                    </div>
                )}
            </div>
        );
    };

    const renderPipeLengthSummary = () => {
        if (!pipeLengthSummary) return null;

        return (
            <div className="pipe-length-summary">
                <div className="summary-header">
                    <h3>🔧 PIPE 자재 길이 요약</h3>
                    <button 
                        className="btn-recalculate"
                        onClick={handleRecalculatePipeLengths}
                        disabled={loading}
                    >
                        🔄 길이 재계산
                    </button>
                </div>
                
                <div className="pipe-stats">
                    <span>총 라인: {pipeLengthSummary.total_lines}개</span>
                    <span>총 길이: {pipeLengthSummary.total_length?.toFixed(2)}m</span>
                </div>

                <div className="pipe-lines">
                    {pipeLengthSummary.pipe_lines?.map((line, idx) => (
                        <div key={idx} className={`pipe-line ${line.purchase_status}`}>
                            <div className="line-info">
                                <span className="drawing-line">
                                    {line.drawing_name} - {line.line_no}
                                </span>
                                <span className="material-spec">
                                    {line.material_grade} {line.schedule} {line.nominal_size}
                                </span>
                            </div>
                            <div className="line-stats">
                                <span className="length">길이: {line.total_length?.toFixed(2)}m</span>
                                <span className="segments">구간: {line.segment_count}개</span>
                                <span className={`status ${line.purchase_status}`}>
                                    {line.purchase_status === 'purchased' ? '구매완료' : 
                                     line.purchase_status === 'pending' ? '구매대기' : '혼재'}
                                </span>
                            </div>
                        </div>
                    ))}
                </div>
            </div>
        );
    };

    // 카테고리별 페이지 렌더링
    if (selectedCategory && currentFile && previousFile) {
        const categoryProps = {
            jobNo: selectedJob,
            fileId: parseInt(currentFile),
            previousFileId: parseInt(previousFile),
            onNavigate: (page) => {
                if (page === 'enhanced-revision') {
                    setSelectedCategory('');
                } else {
                    onNavigate(page);
                }
            },
            user
        };

        switch (selectedCategory) {
            case 'FITTING':
                return <FittingRevisionPage {...categoryProps} />;
            case 'FLANGE':
                return <FlangeRevisionPage {...categoryProps} />;
            case 'SPECIAL':
                return <SpecialRevisionPage {...categoryProps} />;
            case 'SUPPORT':
                return <SupportRevisionPage {...categoryProps} />;
            case 'UNCLASSIFIED':
                return <UnclassifiedRevisionPage {...categoryProps} />;
            case 'VALVE':
                return <ValveRevisionPage {...categoryProps} />;
            case 'GASKET':
                return <GasketRevisionPage {...categoryProps} />;
            case 'BOLT':
                return <BoltRevisionPage {...categoryProps} />;
            case 'PIPE':
                return <PipeCuttingPlanPage {...categoryProps} />;
            default:
                setSelectedCategory('');
                break;
        }
    }

    return (
        <div className="materials-page">
            {/* 헤더 */}
            <div className="materials-header">
                <div className="header-left">
                    <button 
                        className="back-button"
                        onClick={() => onNavigate ? onNavigate('dashboard') : window.history.back()}
                    >
                        ← 뒤로가기
                    </button>
                    <div className="header-center">
                        <h1 style={{ margin: 0, fontSize: '24px', fontWeight: '600', color: '#1f2937' }}>
                            🔄 강화된 리비전 관리
                        </h1>
                        <span style={{ color: '#6b7280', fontSize: '14px' }}>
                            구매 상태를 고려한 스마트 리비전 비교
                        </span>
                    </div>
                </div>
            </div>

            {error && <ErrorMessage message={error} onClose={() => setError('')} />}

            {/* 메인 콘텐츠 */}
            <div className="materials-content">
                <div className="control-section">
                    <div className="section-header">
                        <h3>📂 비교 설정</h3>
                    </div>
                    <div className="control-grid">
                        <div className="control-group">
                            <label>작업 선택:</label>
                            <select 
                                value={selectedJob} 
                                onChange={(e) => setSelectedJob(e.target.value)}
                                disabled={loading}
                            >
                                <option value="">작업을 선택하세요</option>
                                {jobs.map(job => (
                                    <option key={job.job_no} value={job.job_no}>
                                        {job.job_no} - {job.job_name}
                                    </option>
                                ))}
                            </select>
                        </div>

                        <div className="control-group">
                            <label>현재 파일:</label>
                            <select 
                                value={currentFile} 
                                onChange={(e) => setCurrentFile(e.target.value)}
                                disabled={loading || !selectedJob}
                            >
                                <option value="">현재 파일을 선택하세요</option>
                                {files.map(file => (
                                    <option key={file.id} value={file.id}>
                                        {file.original_filename} ({file.revision})
                                    </option>
                                ))}
                            </select>
                        </div>

                        <div className="control-group">
                            <label>이전 파일 (선택사항):</label>
                            <select 
                                value={previousFile} 
                                onChange={(e) => setPreviousFile(e.target.value)}
                                disabled={loading || !selectedJob}
                            >
                                <option value="">자동 탐지</option>
                                {files.filter(f => f.id !== parseInt(currentFile)).map(file => (
                                    <option key={file.id} value={file.id}>
                                        {file.original_filename} ({file.revision})
                                    </option>
                                ))}
                            </select>
                        </div>

                        <div className="control-group">
                            <button 
                                className="btn-compare"
                                onClick={handleCompareRevisions}
                                disabled={loading || !selectedJob || !currentFile}
                            >
                                {loading ? <LoadingSpinner size="small" /> : '🔍 리비전 비교'}
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <div className="revision-content">
                <div className="content-left">
                    {/* 비교 결과 */}
                    {comparisonResult && (
                        <div className="comparison-result">
                            <div className="result-header">
                                <h3>📊 비교 결과</h3>
                                {comparisonResult.comparison_id && (
                                    <button 
                                        className="btn-apply"
                                        onClick={() => {
                                            setSelectedComparison(comparisonResult.comparison_id);
                                            setShowApplyDialog(true);
                                        }}
                                        disabled={loading}
                                    >
                                        ✅ 변경사항 적용
                                    </button>
                                )}
                            </div>
                            
                            {renderComparisonSummary(comparisonResult.summary)}
                            {renderChangeDetails(comparisonResult.changes)}
                        </div>
                    )}

                    {/* PIPE 길이 요약 */}
                    {renderPipeLengthSummary()}

                    {/* 카테고리별 자재 관리 */}
                    {currentFile && previousFile && Object.keys(categoryMaterials).length > 0 && (
                        <div className="category-materials-section">
                            <h3>📂 카테고리별 리비전 관리</h3>
                            <div className="category-grid">
                                {[
                                    { key: 'PIPE', name: 'PIPE', icon: '🔧', description: 'Cutting Plan 관리' },
                                    { key: 'FITTING', name: 'FITTING', icon: '🔧', description: '피팅 자재' },
                                    { key: 'FLANGE', name: 'FLANGE', icon: '🔩', description: '플랜지 자재' },
                                    { key: 'VALVE', name: 'VALVE', icon: '🚰', description: '밸브 자재' },
                                    { key: 'GASKET', name: 'GASKET', icon: '⭕', description: '가스켓 자재' },
                                    { key: 'BOLT', name: 'BOLT', icon: '🔩', description: '볼트 자재' },
                                    { key: 'SUPPORT', name: 'SUPPORT', icon: '🏗️', description: '지지대 자재' },
                                    { key: 'SPECIAL', name: 'SPECIAL', icon: '⭐', description: '특수 자재' },
                                    { key: 'UNCLASSIFIED', name: 'UNCLASSIFIED', icon: '❓', description: '미분류 자재' }
                                ].map(category => {
                                    const stats = categoryMaterials[category.key] || { count: 0, processing_info: {} };
                                    const hasRevisionMaterials = stats.processing_info?.by_status?.REVISION_MATERIAL > 0;
                                    
                                    return (
                                        <div 
                                            key={category.key}
                                            className={`category-card ${hasRevisionMaterials ? 'has-revisions' : ''}`}
                                            onClick={() => stats.count > 0 && setSelectedCategory(category.key)}
                                            style={{ cursor: stats.count > 0 ? 'pointer' : 'not-allowed' }}
                                        >
                                            <div className="category-header">
                                                <span className="category-icon">{category.icon}</span>
                                                <div className="category-info">
                                                    <h4>{category.name}</h4>
                                                    <span className="category-desc">{category.description}</span>
                                                </div>
                                            </div>
                                            <div className="category-stats">
                                                <div className="stat-item">
                                                    <span className="stat-label">전체</span>
                                                    <span className="stat-value">{stats.count}</span>
                                                </div>
                                                {hasRevisionMaterials && (
                                                    <div className="stat-item revision">
                                                        <span className="stat-label">리비전</span>
                                                        <span className="stat-value">{stats.processing_info.by_status.REVISION_MATERIAL}</span>
                                                    </div>
                                                )}
                                                {stats.processing_info?.by_status?.INVENTORY_MATERIAL > 0 && (
                                                    <div className="stat-item inventory">
                                                        <span className="stat-label">재고</span>
                                                        <span className="stat-value">{stats.processing_info.by_status.INVENTORY_MATERIAL}</span>
                                                    </div>
                                                )}
                                            </div>
                                            {stats.count === 0 && (
                                                <div className="empty-category">자료 없음</div>
                                            )}
                                        </div>
                                    );
                                })}
                            </div>
                        </div>
                    )}
                </div>

                <div className="content-right">
                    {/* 비교 이력 */}
                    <div className="comparison-history">
                        <h3>📋 비교 이력</h3>
                        {comparisonHistory.length > 0 ? (
                            <div className="history-list">
                                {comparisonHistory.map(comp => (
                                    <div key={comp.id} className={`history-item ${comp.is_applied ? 'applied' : 'pending'}`}>
                                        <div className="history-header">
                                            <span className="comparison-date">
                                                {new Date(comp.comparison_date).toLocaleString()}
                                            </span>
                                            <span className={`status ${comp.is_applied ? 'applied' : 'pending'}`}>
                                                {comp.is_applied ? '적용완료' : '대기중'}
                                            </span>
                                        </div>
                                        <div className="history-summary">
                                            {comp.summary_stats && (
                                                <>
                                                    <span>구매완료 변경: {comp.summary_stats.purchased_increased + comp.summary_stats.purchased_decreased}</span>
                                                    <span>구매미완료 변경: {comp.summary_stats.unpurchased_increased + comp.summary_stats.unpurchased_decreased}</span>
                                                    <span>신규/삭제: {comp.summary_stats.new_materials + comp.summary_stats.deleted_materials}</span>
                                                </>
                                            )}
                                        </div>
                                        {!comp.is_applied && (
                                            <button 
                                                className="btn-apply-small"
                                                onClick={() => {
                                                    setSelectedComparison(comp.id);
                                                    setShowApplyDialog(true);
                                                }}
                                                disabled={loading}
                                            >
                                                적용
                                            </button>
                                        )}
                                    </div>
                                ))}
                            </div>
                        ) : (
                            <p className="no-history">비교 이력이 없습니다.</p>
                        )}
                    </div>
                </div>
            </div>

            {/* 적용 확인 다이얼로그 */}
            <ConfirmDialog
                isOpen={showApplyDialog}
                title="변경사항 적용 확인"
                message="리비전 변경사항을 실제 데이터베이스에 적용하시겠습니까? 이 작업은 되돌릴 수 없습니다."
                onConfirm={() => handleApplyChanges(selectedComparison)}
                onCancel={() => {
                    setShowApplyDialog(false);
                    setSelectedComparison(null);
                }}
                confirmText="적용"
                cancelText="취소"
            />
        </div>
    );
};

export default EnhancedRevisionPage;
