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

const FittingRevisionManager = ({ 
    currentFileId, 
    previousFileId, 
    jobNo, 
    onRevisionComplete,
    materials = [] 
}) => {
    const [fittingComparison, setFittingComparison] = useState(null);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState('');

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

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

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

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

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

    const renderFittingChanges = () => {
        if (!fittingComparison?.changes) return null;

        const changes = fittingComparison.changes;
        
        return (
            <div className="fitting-changes">
                <h4>🔩 FITTING 자재 변경사항</h4>
                
                {/* 구매 완료 FITTING 변경사항 */}
                {changes.purchased_materials?.additional_purchase_needed?.length > 0 && (
                    <div className="change-section purchased-fittings">
                        <h5>📈 추가 구매 필요 (구매완료 FITTING)</h5>
                        <div className="fitting-list">
                            {changes.purchased_materials.additional_purchase_needed
                                .filter(item => item.material.classified_category === 'FITTING')
                                .map((item, idx) => (
                                <div key={idx} className="fitting-item additional-purchase">
                                    <div className="fitting-info">
                                        <span className="fitting-desc">
                                            {item.material.original_description}
                                        </span>
                                        <span className="fitting-spec">
                                            {item.material.material_grade} {item.material.main_nom}
                                        </span>
                                    </div>
                                    <div className="quantity-change">
                                        <span className="previous">이전: {item.previous_quantity}개</span>
                                        <span className="arrow">→</span>
                                        <span className="current">현재: {item.current_quantity}개</span>
                                        <span className="additional">추가: +{item.additional_needed}개</span>
                                    </div>
                                    <div className="action-required">
                                        ⚠️ 추가 구매 필요
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                )}

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

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

                {/* 신규 FITTING */}
                {changes.new_materials?.filter(item => item.material.classified_category === 'FITTING').length > 0 && (
                    <div className="change-section new-fittings">
                        <h5>✅ 신규 FITTING</h5>
                        <div className="fitting-list">
                            {changes.new_materials
                                .filter(item => item.material.classified_category === 'FITTING')
                                .map((item, idx) => (
                                <div key={idx} className="fitting-item new-material">
                                    <div className="fitting-info">
                                        <span className="fitting-desc">
                                            {item.material.original_description}
                                        </span>
                                        <span className="fitting-spec">
                                            {item.material.material_grade} {item.material.main_nom}
                                        </span>
                                    </div>
                                    <div className="quantity-info">
                                        <span className="quantity">수량: {item.material.quantity}개</span>
                                    </div>
                                    <div className="action-required">
                                        🆕 신규 구매 필요
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                )}

                {/* 삭제된 FITTING */}
                {changes.deleted_materials?.filter(item => item.material.classified_category === 'FITTING').length > 0 && (
                    <div className="change-section deleted-fittings">
                        <h5>❌ 삭제된 FITTING</h5>
                        <div className="fitting-list">
                            {changes.deleted_materials
                                .filter(item => item.material.classified_category === 'FITTING')
                                .map((item, idx) => (
                                <div key={idx} className="fitting-item deleted-material">
                                    <div className="fitting-info">
                                        <span className="fitting-desc">
                                            {item.material.original_description}
                                        </span>
                                        <span className="fitting-spec">
                                            {item.material.material_grade} {item.material.main_nom}
                                        </span>
                                    </div>
                                    <div className="quantity-info">
                                        <span className="quantity">이전 수량: {item.material.quantity}개</span>
                                    </div>
                                    <div className="action-required">
                                        🗑️ 리비전에서 제거됨
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                )}
            </div>
        );
    };

    const renderFittingSummary = () => {
        const totalFittings = fittingMaterials.length;
        const purchasedFittings = fittingMaterials.filter(m => m.purchase_confirmed).length;
        const pendingFittings = totalFittings - purchasedFittings;

        return (
            <div className="fitting-summary">
                <h4>🔩 FITTING 요약</h4>
                <div className="summary-stats">
                    <div className="stat-card">
                        <span className="stat-label">총 FITTING</span>
                        <span className="stat-value">{totalFittings}개</span>
                    </div>
                    <div className="stat-card">
                        <span className="stat-label">구매완료</span>
                        <span className="stat-value">{purchasedFittings}개</span>
                    </div>
                    <div className="stat-card">
                        <span className="stat-label">구매대기</span>
                        <span className="stat-value">{pendingFittings}개</span>
                    </div>
                </div>
            </div>
        );
    };

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

            {renderFittingSummary()}
            {renderFittingChanges()}
        </div>
    );
};

export default FittingRevisionManager;
