import { useState, useEffect, useCallback } from 'react';
import { api } from '../api';

/**
 * 리비전 로직 처리 훅
 * 구매 상태별 자재 처리 로직
 */
export const useRevisionLogic = (jobNo, currentFileId, previousFileId = null) => {
    const [processingResult, setProcessingResult] = useState(null);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);

    const processRevision = useCallback(async () => {
        if (!jobNo || !currentFileId) return;

        try {
            setLoading(true);
            setError(null);

            const params = new URLSearchParams({
                job_no: jobNo,
                file_id: currentFileId
            });

            if (previousFileId) {
                params.append('previous_file_id', previousFileId);
            }

            const response = await api.post(`/revision-redirect/process-revision/${jobNo}/${currentFileId}?${params}`);
            
            if (response.data.success) {
                setProcessingResult(response.data.data);
            }
        } catch (err) {
            console.error('리비전 처리 실패:', err);
            setError(err.message);
        } finally {
            setLoading(false);
        }
    }, [jobNo, currentFileId, previousFileId]);

    const applyProcessingResults = useCallback(async (results) => {
        try {
            setLoading(true);
            setError(null);

            const response = await api.post('/revision-material/apply-results', {
                processing_results: results
            });

            if (response.data.success) {
                return response.data;
            } else {
                throw new Error(response.data.message || '처리 결과 적용 실패');
            }
        } catch (err) {
            console.error('처리 결과 적용 실패:', err);
            setError(err.message);
            throw err;
        } finally {
            setLoading(false);
        }
    }, []);

    return {
        processingResult,
        loading,
        error,
        processRevision,
        applyProcessingResults,
        setError
    };
};

/**
 * 카테고리별 자재 처리 훅
 */
export const useCategoryMaterialProcessing = (fileId, category) => {
    const [materials, setMaterials] = useState([]);
    const [processingInfo, setProcessingInfo] = useState({});
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);

    const loadCategoryMaterials = useCallback(async () => {
        if (!fileId || !category || category === 'PIPE') return;

        try {
            setLoading(true);
            setError(null);

            const response = await api.get(`/revision-material/category/${fileId}/${category}`);
            
            if (response.data.success) {
                setMaterials(response.data.data.materials || []);
                setProcessingInfo(response.data.data.processing_info || {});
            }
        } catch (err) {
            console.error('카테고리 자재 조회 실패:', err);
            setError(err.message);
        } finally {
            setLoading(false);
        }
    }, [fileId, category]);

    const processMaterial = useCallback(async (materialId, action, additionalData = {}) => {
        try {
            const response = await api.post(`/revision-material/process/${materialId}`, {
                action,
                ...additionalData
            });

            if (response.data.success) {
                // 자재 목록 새로고침
                await loadCategoryMaterials();
                return response.data;
            } else {
                throw new Error(response.data.message || '자재 처리 실패');
            }
        } catch (err) {
            console.error('자재 처리 실패:', err);
            setError(err.message);
            throw err;
        }
    }, [loadCategoryMaterials]);

    const updateMaterialStatus = useCallback((materialId, newStatus, additionalInfo = {}) => {
        setMaterials(prev => 
            prev.map(material => 
                material.id === materialId 
                    ? { 
                        ...material, 
                        revision_status: newStatus,
                        processing_info: {
                            ...material.processing_info,
                            ...additionalInfo
                        }
                    }
                    : material
            )
        );
    }, []);

    useEffect(() => {
        loadCategoryMaterials();
    }, [loadCategoryMaterials]);

    return {
        materials,
        processingInfo,
        loading,
        error,
        loadCategoryMaterials,
        processMaterial,
        updateMaterialStatus,
        setError
    };
};

/**
 * 자재 선택 및 일괄 처리 훅
 */
export const useMaterialSelection = (materials = []) => {
    const [selectedMaterials, setSelectedMaterials] = useState(new Set());
    const [selectAll, setSelectAll] = useState(false);

    const toggleMaterial = useCallback((materialId) => {
        setSelectedMaterials(prev => {
            const newSet = new Set(prev);
            if (newSet.has(materialId)) {
                newSet.delete(materialId);
            } else {
                newSet.add(materialId);
            }
            return newSet;
        });
    }, []);

    const toggleSelectAll = useCallback(() => {
        if (selectAll) {
            setSelectedMaterials(new Set());
        } else {
            const selectableMaterials = materials
                .filter(material => material.processing_info?.action !== '완료')
                .map(material => material.id);
            setSelectedMaterials(new Set(selectableMaterials));
        }
        setSelectAll(!selectAll);
    }, [selectAll, materials]);

    const clearSelection = useCallback(() => {
        setSelectedMaterials(new Set());
        setSelectAll(false);
    }, []);

    const getSelectedMaterials = useCallback(() => {
        return materials.filter(material => selectedMaterials.has(material.id));
    }, [materials, selectedMaterials]);

    const getSelectionSummary = useCallback(() => {
        const selected = getSelectedMaterials();
        const byStatus = selected.reduce((acc, material) => {
            const status = material.processing_info?.display_status || 'UNKNOWN';
            acc[status] = (acc[status] || 0) + 1;
            return acc;
        }, {});

        return {
            total: selected.length,
            byStatus,
            canProcess: selected.length > 0
        };
    }, [getSelectedMaterials]);

    // materials 변경 시 selectAll 상태 업데이트
    useEffect(() => {
        const selectableMaterials = materials
            .filter(material => material.processing_info?.action !== '완료');
        
        if (selectableMaterials.length === 0) {
            setSelectAll(false);
        } else {
            const allSelected = selectableMaterials.every(material => 
                selectedMaterials.has(material.id)
            );
            setSelectAll(allSelected);
        }
    }, [materials, selectedMaterials]);

    return {
        selectedMaterials,
        selectAll,
        toggleMaterial,
        toggleSelectAll,
        clearSelection,
        getSelectedMaterials,
        getSelectionSummary
    };
};

/**
 * 리비전 처리 상태 추적 훅
 */
export const useRevisionProcessingStatus = (jobNo, fileId) => {
    const [status, setStatus] = useState(null);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);

    const loadStatus = useCallback(async () => {
        if (!jobNo || !fileId) return;

        try {
            setLoading(true);
            setError(null);

            const response = await api.get(`/revision-status/${jobNo}/${fileId}`);
            
            if (response.data.success) {
                setStatus(response.data.data);
            }
        } catch (err) {
            console.error('리비전 상태 조회 실패:', err);
            setError(err.message);
        } finally {
            setLoading(false);
        }
    }, [jobNo, fileId]);

    const updateProcessingProgress = useCallback((category, processed, total) => {
        setStatus(prev => {
            if (!prev) return prev;

            const newCategoryStatus = {
                ...prev.processing_status.category_breakdown[category],
                processed,
                pending: total - processed
            };

            const newCategoryBreakdown = {
                ...prev.processing_status.category_breakdown,
                [category]: newCategoryStatus
            };

            // 전체 통계 재계산
            const totalProcessed = Object.values(newCategoryBreakdown)
                .reduce((sum, cat) => sum + cat.processed, 0);
            const totalMaterials = Object.values(newCategoryBreakdown)
                .reduce((sum, cat) => sum + cat.total, 0);

            return {
                ...prev,
                processing_status: {
                    ...prev.processing_status,
                    total_processed: totalProcessed,
                    pending_processing: totalMaterials - totalProcessed,
                    completion_percentage: totalMaterials > 0 ? (totalProcessed / totalMaterials * 100) : 0,
                    category_breakdown: newCategoryBreakdown
                }
            };
        });
    }, []);

    useEffect(() => {
        loadStatus();
    }, [loadStatus]);

    return {
        status,
        loading,
        error,
        loadStatus,
        updateProcessingProgress,
        setError
    };
};
