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

/**
 * 리비전 비교 훅
 * 두 리비전 간의 자재 비교 및 차이점 분석
 */
export const useRevisionComparison = () => {
    const [comparisonResult, setComparisonResult] = useState(null);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);

    const compareRevisions = useCallback(async (currentFileId, previousFileId, categoryFilter = null) => {
        try {
            setLoading(true);
            setError(null);

            const params = new URLSearchParams({
                current_file_id: currentFileId,
                previous_file_id: previousFileId
            });

            if (categoryFilter) {
                params.append('category_filter', categoryFilter);
            }

            const response = await api.post(`/revision-comparison/compare?${params}`);
            
            if (response.data.success) {
                setComparisonResult(response.data.data);
                return response.data.data;
            } else {
                throw new Error(response.data.message || '리비전 비교 실패');
            }
        } catch (err) {
            console.error('리비전 비교 실패:', err);
            setError(err.message);
            throw err;
        } finally {
            setLoading(false);
        }
    }, []);

    const getCategoryComparison = useCallback(async (currentFileId, previousFileId, category) => {
        if (category === 'PIPE') {
            console.warn('PIPE 카테고리는 별도 처리가 필요합니다.');
            return null;
        }

        return await compareRevisions(currentFileId, previousFileId, category);
    }, [compareRevisions]);

    const getComparisonSummary = useCallback((comparison) => {
        if (!comparison || !comparison.summary) return null;

        const { summary } = comparison;
        
        return {
            totalChanges: summary.modified + summary.added + summary.removed,
            unchanged: summary.unchanged,
            modified: summary.modified,
            added: summary.added,
            removed: summary.removed,
            changePercentage: summary.previous_count > 0 
                ? ((summary.modified + summary.added + summary.removed) / summary.previous_count * 100)
                : 0,
            hasSignificantChanges: (summary.modified + summary.added + summary.removed) > 0
        };
    }, []);

    const getChangesByType = useCallback((comparison, changeType) => {
        if (!comparison || !comparison.changes) return [];
        return comparison.changes[changeType] || [];
    }, []);

    const getMaterialChanges = useCallback((comparison, materialId) => {
        if (!comparison || !comparison.changes) return null;

        // 모든 변경 타입에서 해당 자재 찾기
        for (const [changeType, changes] of Object.entries(comparison.changes)) {
            const materialChange = changes.find(change => {
                const material = change.material || change.current || change.previous;
                return material && material.id === materialId;
            });
            
            if (materialChange) {
                return {
                    changeType,
                    ...materialChange
                };
            }
        }
        
        return null;
    }, []);

    const filterChangesByCategory = useCallback((comparison, category) => {
        if (!comparison || !comparison.changes) return null;

        const filteredChanges = {};
        
        for (const [changeType, changes] of Object.entries(comparison.changes)) {
            filteredChanges[changeType] = changes.filter(change => {
                const material = change.material || change.current || change.previous;
                return material && material.classified_category === category;
            });
        }

        // 필터링된 요약 통계 계산
        const filteredSummary = {
            unchanged: filteredChanges.unchanged?.length || 0,
            modified: filteredChanges.modified?.length || 0,
            added: filteredChanges.added?.length || 0,
            removed: filteredChanges.removed?.length || 0
        };

        return {
            ...comparison,
            changes: filteredChanges,
            summary: {
                ...comparison.summary,
                ...filteredSummary,
                category_filter: category
            }
        };
    }, []);

    const exportComparisonReport = useCallback(async (comparison, format = 'excel') => {
        try {
            setLoading(true);
            
            const response = await api.post('/revision-comparison/export', {
                comparison_data: comparison,
                format
            }, {
                responseType: 'blob'
            });

            // 파일 다운로드
            const blob = new Blob([response.data], {
                type: format === 'excel' 
                    ? 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                    : 'application/pdf'
            });
            
            const url = window.URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = `revision_comparison_${new Date().toISOString().split('T')[0]}.${format === 'excel' ? 'xlsx' : 'pdf'}`;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            window.URL.revokeObjectURL(url);

            return true;
        } catch (err) {
            console.error('비교 보고서 내보내기 실패:', err);
            setError(err.message);
            return false;
        } finally {
            setLoading(false);
        }
    }, []);

    const clearComparison = useCallback(() => {
        setComparisonResult(null);
        setError(null);
    }, []);

    return {
        comparisonResult,
        loading,
        error,
        compareRevisions,
        getCategoryComparison,
        getComparisonSummary,
        getChangesByType,
        getMaterialChanges,
        filterChangesByCategory,
        exportComparisonReport,
        clearComparison,
        setError
    };
};

/**
 * 리비전 차이점 시각화 훅
 */
export const useRevisionVisualization = (comparison) => {
    const getChangeVisualizationData = useCallback(() => {
        if (!comparison || !comparison.summary) return null;

        const { summary } = comparison;
        
        return {
            pieChart: [
                { name: '변경없음', value: summary.unchanged, color: '#10b981' },
                { name: '수정됨', value: summary.modified, color: '#f59e0b' },
                { name: '추가됨', value: summary.added, color: '#3b82f6' },
                { name: '제거됨', value: summary.removed, color: '#ef4444' }
            ].filter(item => item.value > 0),
            
            barChart: {
                categories: ['변경없음', '수정됨', '추가됨', '제거됨'],
                data: [summary.unchanged, summary.modified, summary.added, summary.removed],
                colors: ['#10b981', '#f59e0b', '#3b82f6', '#ef4444']
            },
            
            summary: {
                totalItems: summary.previous_count + summary.added,
                changeRate: summary.previous_count > 0 
                    ? ((summary.modified + summary.added + summary.removed) / summary.previous_count * 100)
                    : 0,
                stabilityRate: summary.previous_count > 0 
                    ? (summary.unchanged / summary.previous_count * 100)
                    : 0
            }
        };
    }, [comparison]);

    const getCategoryBreakdown = useCallback(() => {
        if (!comparison || !comparison.changes) return null;

        const categoryStats = {};
        
        // 모든 변경사항을 카테고리별로 분류
        Object.entries(comparison.changes).forEach(([changeType, changes]) => {
            changes.forEach(change => {
                const material = change.material || change.current || change.previous;
                const category = material?.classified_category || 'UNKNOWN';
                
                if (!categoryStats[category]) {
                    categoryStats[category] = {
                        unchanged: 0,
                        modified: 0,
                        added: 0,
                        removed: 0,
                        total: 0
                    };
                }
                
                categoryStats[category][changeType]++;
                categoryStats[category].total++;
            });
        });

        return Object.entries(categoryStats).map(([category, stats]) => ({
            category,
            ...stats,
            changeRate: stats.total > 0 ? ((stats.modified + stats.added + stats.removed) / stats.total * 100) : 0
        }));
    }, [comparison]);

    const getTimelineData = useCallback(() => {
        if (!comparison) return null;

        return {
            comparisonDate: comparison.comparison_date,
            previousVersion: {
                fileId: comparison.previous_file_id,
                materialCount: comparison.summary?.previous_count || 0
            },
            currentVersion: {
                fileId: comparison.current_file_id,
                materialCount: comparison.summary?.current_count || 0
            },
            changes: {
                added: comparison.summary?.added || 0,
                removed: comparison.summary?.removed || 0,
                modified: comparison.summary?.modified || 0
            }
        };
    }, [comparison]);

    return {
        getChangeVisualizationData,
        getCategoryBreakdown,
        getTimelineData
    };
};

/**
 * 리비전 비교 필터링 훅
 */
export const useRevisionFiltering = (comparison) => {
    const [filters, setFilters] = useState({
        category: 'all',
        changeType: 'all',
        searchTerm: '',
        showOnlySignificant: false
    });

    const updateFilter = useCallback((filterName, value) => {
        setFilters(prev => ({
            ...prev,
            [filterName]: value
        }));
    }, []);

    const getFilteredChanges = useCallback(() => {
        if (!comparison || !comparison.changes) return null;

        let filteredChanges = { ...comparison.changes };

        // 카테고리 필터
        if (filters.category !== 'all') {
            Object.keys(filteredChanges).forEach(changeType => {
                filteredChanges[changeType] = filteredChanges[changeType].filter(change => {
                    const material = change.material || change.current || change.previous;
                    return material?.classified_category === filters.category;
                });
            });
        }

        // 변경 타입 필터
        if (filters.changeType !== 'all') {
            const selectedChanges = filteredChanges[filters.changeType] || [];
            filteredChanges = {
                unchanged: filters.changeType === 'unchanged' ? selectedChanges : [],
                modified: filters.changeType === 'modified' ? selectedChanges : [],
                added: filters.changeType === 'added' ? selectedChanges : [],
                removed: filters.changeType === 'removed' ? selectedChanges : []
            };
        }

        // 검색어 필터
        if (filters.searchTerm) {
            const searchLower = filters.searchTerm.toLowerCase();
            Object.keys(filteredChanges).forEach(changeType => {
                filteredChanges[changeType] = filteredChanges[changeType].filter(change => {
                    const material = change.material || change.current || change.previous;
                    const description = material?.original_description || '';
                    return description.toLowerCase().includes(searchLower);
                });
            });
        }

        // 중요한 변경사항만 표시
        if (filters.showOnlySignificant) {
            Object.keys(filteredChanges).forEach(changeType => {
                if (changeType === 'unchanged') {
                    filteredChanges[changeType] = []; // 변경없는 항목 제외
                } else {
                    filteredChanges[changeType] = filteredChanges[changeType].filter(change => {
                        // 수량 변화가 큰 경우만 표시
                        const changes = change.changes || {};
                        const quantityChange = changes.quantity?.change || 0;
                        return Math.abs(quantityChange) > 1; // 1개 이상 변경된 경우만
                    });
                }
            });
        }

        return filteredChanges;
    }, [comparison, filters]);

    const getFilterSummary = useCallback(() => {
        const filteredChanges = getFilteredChanges();
        if (!filteredChanges) return null;

        const summary = {
            unchanged: filteredChanges.unchanged?.length || 0,
            modified: filteredChanges.modified?.length || 0,
            added: filteredChanges.added?.length || 0,
            removed: filteredChanges.removed?.length || 0
        };

        summary.total = summary.unchanged + summary.modified + summary.added + summary.removed;

        return summary;
    }, [getFilteredChanges]);

    const resetFilters = useCallback(() => {
        setFilters({
            category: 'all',
            changeType: 'all',
            searchTerm: '',
            showOnlySignificant: false
        });
    }, []);

    return {
        filters,
        updateFilter,
        getFilteredChanges,
        getFilterSummary,
        resetFilters
    };
};
