import React, { useState, useEffect } from 'react';
import { api } from '../../api';
import { LoadingSpinner, ErrorMessage } from '../common';

const PipeRevisionManager = ({ 
    currentFileId, 
    previousFileId, 
    jobNo, 
    onRevisionComplete,
    materials = [] 
}) => {
    const [pipeComparison, setPipeComparison] = useState(null);
    const [pipeLengthSummary, setPipeLengthSummary] = useState(null);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState('');

    // PIPE 자재만 필터링
    const pipeMaterials = materials.filter(m => m.classified_category === 'PIPE');

    useEffect(() => {
        if (currentFileId) {
            loadPipeLengthSummary();
        }
    }, [currentFileId]);

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

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

        try {
            const params = {
                job_no: jobNo,
                current_file_id: currentFileId,
                category_filter: 'PIPE',
                save_comparison: true
            };

            if (previousFileId) {
                params.previous_file_id = previousFileId;
            }

            const response = await api.post('/enhanced-revision/compare-revisions', null, { params });
            setPipeComparison(response.data.data);
            
            if (onRevisionComplete) {
                onRevisionComplete('PIPE', response.data.data);
            }
            
        } catch (err) {
            setError('PIPE 리비전 비교 실패: ' + err.message);
        } finally {
            setLoading(false);
        }
    };

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

    const renderPipeChanges = () => {
        if (!pipeComparison?.changes) return null;

        const changes = pipeComparison.changes;
        
        return (
            <div className="pipe-changes">
                <h4>🔧 PIPE 자재 변경사항</h4>
                
                {/* 구매 완료 PIPE 변경사항 */}
                {changes.purchased_materials?.additional_purchase_needed?.length > 0 && (
                    <div className="change-section purchased-pipes">
                        <h5>📈 추가 구매 필요 (구매완료 PIPE)</h5>
                        <div className="pipe-list">
                            {changes.purchased_materials.additional_purchase_needed
                                .filter(item => item.material.classified_category === 'PIPE')
                                .map((item, idx) => (
                                <div key={idx} className="pipe-item additional-purchase">
                                    <div className="pipe-info">
                                        <span className="drawing-line">
                                            {item.material.drawing_name} - {item.material.line_no}
                                        </span>
                                        <span className="pipe-spec">
                                            {item.material.material_grade} {item.material.schedule} {item.material.main_nom}
                                        </span>
                                    </div>
                                    <div className="length-change">
                                        <span className="previous">이전: {item.previous_quantity}m</span>
                                        <span className="arrow">→</span>
                                        <span className="current">현재: {item.current_quantity}m</span>
                                        <span className="additional">추가: +{item.additional_needed}m</span>
                                    </div>
                                    <div className="action-required">
                                        ⚠️ 추가 구매 필요
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                )}

                {/* 잉여 재고 PIPE */}
                {changes.purchased_materials?.excess_inventory?.length > 0 && (
                    <div className="change-section excess-pipes">
                        <h5>📉 잉여 재고 (구매완료 PIPE)</h5>
                        <div className="pipe-list">
                            {changes.purchased_materials.excess_inventory
                                .filter(item => item.material.classified_category === 'PIPE')
                                .map((item, idx) => (
                                <div key={idx} className="pipe-item excess-inventory">
                                    <div className="pipe-info">
                                        <span className="drawing-line">
                                            {item.material.drawing_name} - {item.material.line_no}
                                        </span>
                                        <span className="pipe-spec">
                                            {item.material.material_grade} {item.material.schedule} {item.material.main_nom}
                                        </span>
                                    </div>
                                    <div className="length-change">
                                        <span className="previous">이전: {item.previous_quantity}m</span>
                                        <span className="arrow">→</span>
                                        <span className="current">현재: {item.current_quantity}m</span>
                                        <span className="excess">잉여: -{item.excess_quantity}m</span>
                                    </div>
                                    <div className="action-required">
                                        📦 재고로 보관
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                )}

                {/* 구매 미완료 PIPE 변경사항 */}
                {changes.unpurchased_materials?.quantity_updated?.length > 0 && (
                    <div className="change-section unpurchased-pipes">
                        <h5>📊 수량 변경 (구매미완료 PIPE)</h5>
                        <div className="pipe-list">
                            {changes.unpurchased_materials.quantity_updated
                                .filter(item => item.material.classified_category === 'PIPE')
                                .map((item, idx) => (
                                <div key={idx} className="pipe-item quantity-updated">
                                    <div className="pipe-info">
                                        <span className="drawing-line">
                                            {item.material.drawing_name} - {item.material.line_no}
                                        </span>
                                        <span className="pipe-spec">
                                            {item.material.material_grade} {item.material.schedule} {item.material.main_nom}
                                        </span>
                                    </div>
                                    <div className="length-change">
                                        <span className="previous">이전: {item.previous_quantity}m</span>
                                        <span className="arrow">→</span>
                                        <span className="current">현재: {item.current_quantity}m</span>
                                    </div>
                                    <div className="action-required">
                                        ✅ 구매 수량 업데이트
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                )}
            </div>
        );
    };

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

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

                <div className="pipe-lines">
                    {pipeLengthSummary.pipe_lines?.slice(0, 5).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>
                    ))}
                    {pipeLengthSummary.pipe_lines?.length > 5 && (
                        <div className="more-lines">
                            ... 외 {pipeLengthSummary.pipe_lines.length - 5}개 라인
                        </div>
                    )}
                </div>
            </div>
        );
    };

    return (
        <div className="pipe-revision-manager">
            {error && <ErrorMessage message={error} onClose={() => setError('')} />}
            
            <div className="pipe-controls">
                <button 
                    className="btn-compare-pipe"
                    onClick={handlePipeRevisionCompare}
                    disabled={loading || !currentFileId}
                >
                    {loading ? <LoadingSpinner size="small" /> : '🔍 PIPE 리비전 비교'}
                </button>
            </div>

            {renderPipeLengthSummary()}
            {renderPipeChanges()}
        </div>
    );
};

export default PipeRevisionManager;
