/**
 * PIPE 이슈 관리 훅
 * 
 * 스냅샷 기반 도면별/단관별 이슈 관리 기능 제공
 */

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

export const usePipeIssue = (jobNo = null, snapshotId = null) => {
    // 상태 관리
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState('');
    
    // 데이터 상태
    const [snapshots, setSnapshots] = useState([]);
    const [currentSnapshot, setCurrentSnapshot] = useState(null);
    const [drawingIssues, setDrawingIssues] = useState([]);
    const [segmentIssues, setSegmentIssues] = useState([]);
    const [issueReport, setIssueReport] = useState(null);
    
    // 필터 상태
    const [selectedArea, setSelectedArea] = useState('');
    const [selectedDrawing, setSelectedDrawing] = useState('');
    const [statusFilter, setStatusFilter] = useState('');
    
    // 스냅샷 목록 조회
    const fetchSnapshots = useCallback(async () => {
        if (!jobNo) return;

        setLoading(true);
        setError('');

        try {
            const response = await api.get(`/pipe-issue/snapshots/${jobNo}`);
            setSnapshots(response.data.snapshots || []);
            
            // 첫 번째 활성 스냅샷을 기본 선택
            const activeSnapshot = response.data.snapshots?.find(s => s.is_locked);
            if (activeSnapshot && !currentSnapshot) {
                setCurrentSnapshot(activeSnapshot);
            }
            
            return response.data;
        } catch (err) {
            const errorMessage = err.response?.data?.detail || '스냅샷 조회 실패';
            setError(errorMessage);
            console.error('스냅샷 조회 실패:', err);
            return null;
        } finally {
            setLoading(false);
        }
    }, [jobNo, currentSnapshot]);

    // 도면 이슈 목록 조회
    const fetchDrawingIssues = useCallback(async (filters = {}) => {
        const targetSnapshotId = filters.snapshotId || snapshotId || currentSnapshot?.snapshot_id;
        if (!targetSnapshotId) return;

        setLoading(true);
        setError('');

        try {
            const params = new URLSearchParams();
            if (filters.area || selectedArea) params.append('area', filters.area || selectedArea);
            if (filters.drawing_name || selectedDrawing) params.append('drawing_name', filters.drawing_name || selectedDrawing);
            if (filters.status_filter || statusFilter) params.append('status_filter', filters.status_filter || statusFilter);

            const response = await api.get(`/pipe-issue/drawing-issues/${targetSnapshotId}?${params}`);
            setDrawingIssues(response.data.issues || []);
            return response.data;
        } catch (err) {
            const errorMessage = err.response?.data?.detail || '도면 이슈 조회 실패';
            setError(errorMessage);
            console.error('도면 이슈 조회 실패:', err);
            return null;
        } finally {
            setLoading(false);
        }
    }, [snapshotId, currentSnapshot, selectedArea, selectedDrawing, statusFilter]);

    // 단관 이슈 목록 조회
    const fetchSegmentIssues = useCallback(async (filters = {}) => {
        const targetSnapshotId = filters.snapshotId || snapshotId || currentSnapshot?.snapshot_id;
        if (!targetSnapshotId) return;

        setLoading(true);
        setError('');

        try {
            const params = new URLSearchParams();
            if (filters.segment_id) params.append('segment_id', filters.segment_id);
            if (filters.status_filter || statusFilter) params.append('status_filter', filters.status_filter || statusFilter);

            const response = await api.get(`/pipe-issue/segment-issues/${targetSnapshotId}?${params}`);
            setSegmentIssues(response.data.issues || []);
            return response.data;
        } catch (err) {
            const errorMessage = err.response?.data?.detail || '단관 이슈 조회 실패';
            setError(errorMessage);
            console.error('단관 이슈 조회 실패:', err);
            return null;
        } finally {
            setLoading(false);
        }
    }, [snapshotId, currentSnapshot, statusFilter]);

    // 도면 이슈 생성
    const createDrawingIssue = useCallback(async (issueData) => {
        const targetSnapshotId = issueData.snapshot_id || snapshotId || currentSnapshot?.snapshot_id;
        if (!targetSnapshotId) {
            setError('스냅샷 ID가 필요합니다.');
            return null;
        }

        setLoading(true);
        setError('');

        try {
            const response = await api.post('/pipe-issue/drawing-issues', {
                ...issueData,
                snapshot_id: targetSnapshotId
            });

            // 목록 새로고침
            await fetchDrawingIssues();
            
            return response.data;
        } catch (err) {
            const errorMessage = err.response?.data?.detail || '도면 이슈 생성 실패';
            setError(errorMessage);
            console.error('도면 이슈 생성 실패:', err);
            return null;
        } finally {
            setLoading(false);
        }
    }, [snapshotId, currentSnapshot, fetchDrawingIssues]);

    // 단관 이슈 생성
    const createSegmentIssue = useCallback(async (issueData) => {
        const targetSnapshotId = issueData.snapshot_id || snapshotId || currentSnapshot?.snapshot_id;
        if (!targetSnapshotId) {
            setError('스냅샷 ID가 필요합니다.');
            return null;
        }

        setLoading(true);
        setError('');

        try {
            const response = await api.post('/pipe-issue/segment-issues', {
                ...issueData,
                snapshot_id: targetSnapshotId
            });

            // 목록 새로고침
            await fetchSegmentIssues();
            
            return response.data;
        } catch (err) {
            const errorMessage = err.response?.data?.detail || '단관 이슈 생성 실패';
            setError(errorMessage);
            console.error('단관 이슈 생성 실패:', err);
            return null;
        } finally {
            setLoading(false);
        }
    }, [snapshotId, currentSnapshot, fetchSegmentIssues]);

    // 도면 이슈 상태 업데이트
    const updateDrawingIssueStatus = useCallback(async (issueId, statusData) => {
        setLoading(true);
        setError('');

        try {
            const response = await api.put(`/pipe-issue/drawing-issues/${issueId}/status`, statusData);

            // 목록 새로고침
            await fetchDrawingIssues();
            
            return response.data;
        } catch (err) {
            const errorMessage = err.response?.data?.detail || '도면 이슈 상태 업데이트 실패';
            setError(errorMessage);
            console.error('도면 이슈 상태 업데이트 실패:', err);
            return null;
        } finally {
            setLoading(false);
        }
    }, [fetchDrawingIssues]);

    // 단관 이슈 상태 업데이트
    const updateSegmentIssueStatus = useCallback(async (issueId, statusData) => {
        setLoading(true);
        setError('');

        try {
            const response = await api.put(`/pipe-issue/segment-issues/${issueId}/status`, statusData);

            // 목록 새로고침
            await fetchSegmentIssues();
            
            return response.data;
        } catch (err) {
            const errorMessage = err.response?.data?.detail || '단관 이슈 상태 업데이트 실패';
            setError(errorMessage);
            console.error('단관 이슈 상태 업데이트 실패:', err);
            return null;
        } finally {
            setLoading(false);
        }
    }, [fetchSegmentIssues]);

    // 이슈 리포트 생성
    const generateIssueReport = useCallback(async () => {
        const targetSnapshotId = snapshotId || currentSnapshot?.snapshot_id;
        if (!targetSnapshotId) return;

        setLoading(true);
        setError('');

        try {
            const response = await api.get(`/pipe-issue/report/${targetSnapshotId}`);
            setIssueReport(response.data);
            return response.data;
        } catch (err) {
            const errorMessage = err.response?.data?.detail || '이슈 리포트 생성 실패';
            setError(errorMessage);
            console.error('이슈 리포트 생성 실패:', err);
            return null;
        } finally {
            setLoading(false);
        }
    }, [snapshotId, currentSnapshot]);

    // 초기 데이터 로드
    useEffect(() => {
        if (jobNo) {
            fetchSnapshots();
        }
    }, [jobNo, fetchSnapshots]);

    // 스냅샷 변경 시 이슈 목록 새로고침
    useEffect(() => {
        if (currentSnapshot?.snapshot_id) {
            fetchDrawingIssues();
            fetchSegmentIssues();
        }
    }, [currentSnapshot, fetchDrawingIssues, fetchSegmentIssues]);

    // 필터 변경 시 이슈 목록 새로고침
    useEffect(() => {
        if (currentSnapshot?.snapshot_id) {
            fetchDrawingIssues();
        }
    }, [selectedArea, selectedDrawing, statusFilter, fetchDrawingIssues]);

    // 편의 함수들
    const getIssueStats = useCallback(() => {
        const totalDrawingIssues = drawingIssues.length;
        const totalSegmentIssues = segmentIssues.length;
        
        const drawingStats = {
            total: totalDrawingIssues,
            open: drawingIssues.filter(i => i.status === 'open').length,
            in_progress: drawingIssues.filter(i => i.status === 'in_progress').length,
            resolved: drawingIssues.filter(i => i.status === 'resolved').length,
            critical: drawingIssues.filter(i => i.severity === 'critical').length,
            high: drawingIssues.filter(i => i.severity === 'high').length
        };

        const segmentStats = {
            total: totalSegmentIssues,
            open: segmentIssues.filter(i => i.status === 'open').length,
            in_progress: segmentIssues.filter(i => i.status === 'in_progress').length,
            resolved: segmentIssues.filter(i => i.status === 'resolved').length,
            critical: segmentIssues.filter(i => i.severity === 'critical').length,
            high: segmentIssues.filter(i => i.severity === 'high').length
        };

        return {
            drawing: drawingStats,
            segment: segmentStats,
            total: totalDrawingIssues + totalSegmentIssues
        };
    }, [drawingIssues, segmentIssues]);

    const hasActiveSnapshot = currentSnapshot && currentSnapshot.is_locked;
    const canManageIssues = hasActiveSnapshot;

    return {
        // 상태
        loading,
        error,
        snapshots,
        currentSnapshot,
        drawingIssues,
        segmentIssues,
        issueReport,

        // 필터
        selectedArea,
        selectedDrawing,
        statusFilter,
        setSelectedArea,
        setSelectedDrawing,
        setStatusFilter,

        // 액션
        fetchSnapshots,
        fetchDrawingIssues,
        fetchSegmentIssues,
        createDrawingIssue,
        createSegmentIssue,
        updateDrawingIssueStatus,
        updateSegmentIssueStatus,
        generateIssueReport,
        setCurrentSnapshot,

        // 편의 함수
        getIssueStats,
        clearError: () => setError(''),
        
        // 상태 확인
        hasActiveSnapshot,
        canManageIssues,
        
        // 통계
        stats: getIssueStats()
    };
};

export default usePipeIssue;
