/**
 * PIPE 단관 이슈 관리 페이지
 * 
 * 스냅샷 기반 도면별/단관별 이슈 관리 UI
 */

import React, { useState, useEffect } from 'react';
import { usePipeIssue } from '../hooks/usePipeIssue';
import { usePipeRevision } from '../hooks/usePipeRevision';
import { LoadingSpinner, ErrorMessage, ConfirmDialog } from '../components/common';
import './PipeIssueManagementPage.css';

const PipeIssueManagementPage = ({ onNavigate, jobNo, fileId }) => {
    // 훅 사용
    const {
        loading,
        error,
        snapshots,
        currentSnapshot,
        drawingIssues,
        segmentIssues,
        selectedArea,
        selectedDrawing,
        statusFilter,
        setSelectedArea,
        setSelectedDrawing,
        setStatusFilter,
        fetchSnapshots,
        createDrawingIssue,
        createSegmentIssue,
        updateDrawingIssueStatus,
        updateSegmentIssueStatus,
        generateIssueReport,
        setCurrentSnapshot,
        stats,
        canManageIssues,
        clearError
    } = usePipeIssue(jobNo);

    const {
        getSnapshotSegments,
        getAvailableAreas,
        getAvailableDrawings
    } = usePipeRevision(jobNo, fileId);

    // 로컬 상태
    const [showCreateDrawingIssue, setShowCreateDrawingIssue] = useState(false);
    const [showCreateSegmentIssue, setShowCreateSegmentIssue] = useState(false);
    const [selectedSegment, setSelectedSegment] = useState(null);
    const [segments, setSegments] = useState([]);
    const [availableAreas, setAvailableAreas] = useState([]);
    const [availableDrawings, setAvailableDrawings] = useState([]);
    const [issueReport, setIssueReport] = useState(null);

    // 도면 이슈 생성 폼 상태
    const [drawingIssueForm, setDrawingIssueForm] = useState({
        area: '',
        drawing_name: '',
        issue_description: '',
        severity: 'medium'
    });

    // 단관 이슈 생성 폼 상태
    const [segmentIssueForm, setSegmentIssueForm] = useState({
        segment_id: '',
        issue_description: '',
        issue_type: 'other',
        length_change: '',
        new_length: '',
        material_change: '',
        severity: 'medium'
    });

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

    // 스냅샷 변경 시 관련 데이터 로드
    useEffect(() => {
        if (currentSnapshot?.snapshot_id) {
            loadSnapshotData();
        }
    }, [currentSnapshot]);

    // 스냅샷 데이터 로드
    const loadSnapshotData = async () => {
        if (!currentSnapshot?.snapshot_id) return;

        try {
            // 구역 목록 로드
            const areasData = await getAvailableAreas(currentSnapshot.snapshot_id);
            setAvailableAreas(areasData?.areas || []);

            // 도면 목록 로드
            const drawingsData = await getAvailableDrawings(currentSnapshot.snapshot_id);
            setAvailableDrawings(drawingsData?.drawings || []);

            // 단관 목록 로드
            const segmentsData = await getSnapshotSegments(currentSnapshot.snapshot_id);
            setSegments(segmentsData?.segments || []);
        } catch (error) {
            console.error('스냅샷 데이터 로드 실패:', error);
        }
    };

    // 구역 변경 시 도면 목록 업데이트
    useEffect(() => {
        if (currentSnapshot?.snapshot_id && selectedArea) {
            const loadDrawings = async () => {
                const drawingsData = await getAvailableDrawings(currentSnapshot.snapshot_id, selectedArea);
                setAvailableDrawings(drawingsData?.drawings || []);
            };
            loadDrawings();
        }
    }, [selectedArea, currentSnapshot, getAvailableDrawings]);

    // 도면 이슈 생성 핸들러
    const handleCreateDrawingIssue = async (e) => {
        e.preventDefault();
        
        if (!drawingIssueForm.area || !drawingIssueForm.drawing_name || !drawingIssueForm.issue_description) {
            alert('모든 필수 필드를 입력해주세요.');
            return;
        }

        const result = await createDrawingIssue(drawingIssueForm);
        if (result) {
            alert('✅ 도면 이슈가 생성되었습니다.');
            setShowCreateDrawingIssue(false);
            setDrawingIssueForm({
                area: '',
                drawing_name: '',
                issue_description: '',
                severity: 'medium'
            });
        }
    };

    // 단관 이슈 생성 핸들러
    const handleCreateSegmentIssue = async (e) => {
        e.preventDefault();
        
        if (!segmentIssueForm.segment_id || !segmentIssueForm.issue_description) {
            alert('모든 필수 필드를 입력해주세요.');
            return;
        }

        const formData = {
            ...segmentIssueForm,
            length_change: segmentIssueForm.length_change ? parseFloat(segmentIssueForm.length_change) : null,
            new_length: segmentIssueForm.new_length ? parseFloat(segmentIssueForm.new_length) : null
        };

        const result = await createSegmentIssue(formData);
        if (result) {
            alert('✅ 단관 이슈가 생성되었습니다.');
            setShowCreateSegmentIssue(false);
            setSegmentIssueForm({
                segment_id: '',
                issue_description: '',
                issue_type: 'other',
                length_change: '',
                new_length: '',
                material_change: '',
                severity: 'medium'
            });
        }
    };

    // 이슈 상태 업데이트 핸들러
    const handleUpdateIssueStatus = async (issueId, issueType, newStatus) => {
        const statusData = {
            status: newStatus,
            resolved_by: newStatus === 'resolved' ? 'user' : null
        };

        let result;
        if (issueType === 'drawing') {
            result = await updateDrawingIssueStatus(issueId, statusData);
        } else {
            result = await updateSegmentIssueStatus(issueId, statusData);
        }

        if (result) {
            alert(`✅ 이슈 상태가 '${newStatus}'로 변경되었습니다.`);
        }
    };

    // 이슈 리포트 생성 핸들러
    const handleGenerateReport = async () => {
        const report = await generateIssueReport();
        if (report) {
            setIssueReport(report);
            alert('✅ 이슈 리포트가 생성되었습니다.');
        }
    };

    // 심각도 배지 색상
    const getSeverityColor = (severity) => {
        switch (severity) {
            case 'critical': return '#dc3545';
            case 'high': return '#fd7e14';
            case 'medium': return '#ffc107';
            case 'low': return '#28a745';
            default: return '#6c757d';
        }
    };

    // 상태 배지 색상
    const getStatusColor = (status) => {
        switch (status) {
            case 'open': return '#dc3545';
            case 'in_progress': return '#ffc107';
            case 'resolved': return '#28a745';
            default: return '#6c757d';
        }
    };

    if (loading) return <LoadingSpinner message="이슈 관리 데이터 로딩 중..." />;

    return (
        <div className="pipe-issue-management-page">
            <div className="page-header">
                <div className="header-content">
                    <h1>🛠️ PIPE 단관 이슈 관리</h1>
                    <p>확정된 Cutting Plan 기준 이슈 관리 (리비전 보호)</p>
                </div>
                <div className="header-actions">
                    <button 
                        className="btn btn-secondary"
                        onClick={() => onNavigate('pipe-cutting-plan')}
                    >
                        ← Cutting Plan으로 돌아가기
                    </button>
                </div>
            </div>

            {error && <ErrorMessage message={error} onClose={clearError} />}

            {/* 스냅샷 정보 */}
            <div className="snapshot-info-section">
                <div className="section-header">
                    <h2>📸 스냅샷 정보</h2>
                </div>
                
                {!canManageIssues ? (
                    <div className="no-snapshot-warning">
                        <div className="warning-icon">⚠️</div>
                        <div className="warning-content">
                            <h3>확정된 Cutting Plan이 없습니다</h3>
                            <p>이슈 관리를 위해서는 먼저 Cutting Plan을 확정해야 합니다.</p>
                            <button 
                                className="btn btn-primary"
                                onClick={() => onNavigate('pipe-cutting-plan')}
                            >
                                Cutting Plan 확정하러 가기
                            </button>
                        </div>
                    </div>
                ) : (
                    <div className="snapshot-card">
                        <div className="snapshot-details">
                            <h3>{currentSnapshot.snapshot_name}</h3>
                            <div className="snapshot-stats">
                                <span className="stat-item">
                                    📊 총 단관: {currentSnapshot.total_segments}개
                                </span>
                                <span className="stat-item">
                                    📋 총 도면: {currentSnapshot.total_drawings}개
                                </span>
                                <span className="stat-item">
                                    🔒 확정일: {new Date(currentSnapshot.locked_at).toLocaleDateString()}
                                </span>
                            </div>
                        </div>
                        <div className="snapshot-actions">
                            <button 
                                className="btn btn-info"
                                onClick={handleGenerateReport}
                            >
                                📊 이슈 리포트 생성
                            </button>
                        </div>
                    </div>
                )}
            </div>

            {canManageIssues && (
                <>
                    {/* 이슈 통계 */}
                    <div className="issue-stats-section">
                        <div className="section-header">
                            <h2>📈 이슈 현황</h2>
                        </div>
                        <div className="stats-grid">
                            <div className="stat-card">
                                <h3>도면 이슈</h3>
                                <div className="stat-number">{stats.drawing.total}</div>
                                <div className="stat-breakdown">
                                    <span className="stat-item open">미해결: {stats.drawing.open}</span>
                                    <span className="stat-item progress">진행중: {stats.drawing.in_progress}</span>
                                    <span className="stat-item resolved">완료: {stats.drawing.resolved}</span>
                                </div>
                            </div>
                            <div className="stat-card">
                                <h3>단관 이슈</h3>
                                <div className="stat-number">{stats.segment.total}</div>
                                <div className="stat-breakdown">
                                    <span className="stat-item open">미해결: {stats.segment.open}</span>
                                    <span className="stat-item progress">진행중: {stats.segment.in_progress}</span>
                                    <span className="stat-item resolved">완료: {stats.segment.resolved}</span>
                                </div>
                            </div>
                            <div className="stat-card">
                                <h3>전체 이슈</h3>
                                <div className="stat-number">{stats.total}</div>
                                <div className="stat-breakdown">
                                    <span className="stat-item critical">긴급: {stats.drawing.critical + stats.segment.critical}</span>
                                    <span className="stat-item high">높음: {stats.drawing.high + stats.segment.high}</span>
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* 필터 및 액션 */}
                    <div className="filter-actions-section">
                        <div className="filters">
                            <select 
                                value={selectedArea} 
                                onChange={(e) => setSelectedArea(e.target.value)}
                                className="filter-select"
                            >
                                <option value="">전체 구역</option>
                                {availableAreas.map(area => (
                                    <option key={area} value={area}>{area}</option>
                                ))}
                            </select>

                            <select 
                                value={selectedDrawing} 
                                onChange={(e) => setSelectedDrawing(e.target.value)}
                                className="filter-select"
                            >
                                <option value="">전체 도면</option>
                                {availableDrawings.map(drawing => (
                                    <option key={drawing} value={drawing}>{drawing}</option>
                                ))}
                            </select>

                            <select 
                                value={statusFilter} 
                                onChange={(e) => setStatusFilter(e.target.value)}
                                className="filter-select"
                            >
                                <option value="">전체 상태</option>
                                <option value="open">미해결</option>
                                <option value="in_progress">진행중</option>
                                <option value="resolved">완료</option>
                            </select>
                        </div>

                        <div className="actions">
                            <button 
                                className="btn btn-primary"
                                onClick={() => setShowCreateDrawingIssue(true)}
                            >
                                📋 도면 이슈 등록
                            </button>
                            <button 
                                className="btn btn-primary"
                                onClick={() => setShowCreateSegmentIssue(true)}
                            >
                                🔧 단관 이슈 등록
                            </button>
                        </div>
                    </div>

                    {/* 도면 이슈 목록 */}
                    <div className="drawing-issues-section">
                        <div className="section-header">
                            <h2>📋 도면 이슈 목록</h2>
                        </div>
                        
                        {drawingIssues.length === 0 ? (
                            <div className="no-issues">
                                <p>등록된 도면 이슈가 없습니다.</p>
                            </div>
                        ) : (
                            <div className="issues-list">
                                {drawingIssues.map(issue => (
                                    <div key={issue.id} className="issue-card drawing-issue">
                                        <div className="issue-header">
                                            <div className="issue-title">
                                                <span className="area-badge">{issue.area}</span>
                                                <span className="drawing-name">{issue.drawing_name}</span>
                                            </div>
                                            <div className="issue-badges">
                                                <span 
                                                    className="severity-badge"
                                                    style={{ backgroundColor: getSeverityColor(issue.severity) }}
                                                >
                                                    {issue.severity}
                                                </span>
                                                <span 
                                                    className="status-badge"
                                                    style={{ backgroundColor: getStatusColor(issue.status) }}
                                                >
                                                    {issue.status}
                                                </span>
                                            </div>
                                        </div>
                                        <div className="issue-content">
                                            <p>{issue.issue_description}</p>
                                        </div>
                                        <div className="issue-footer">
                                            <div className="issue-meta">
                                                <span>보고자: {issue.reported_by}</span>
                                                <span>등록일: {new Date(issue.reported_at).toLocaleDateString()}</span>
                                            </div>
                                            <div className="issue-actions">
                                                {issue.status !== 'resolved' && (
                                                    <>
                                                        <button 
                                                            className="btn btn-sm btn-warning"
                                                            onClick={() => handleUpdateIssueStatus(issue.id, 'drawing', 'in_progress')}
                                                        >
                                                            진행중으로 변경
                                                        </button>
                                                        <button 
                                                            className="btn btn-sm btn-success"
                                                            onClick={() => handleUpdateIssueStatus(issue.id, 'drawing', 'resolved')}
                                                        >
                                                            완료로 변경
                                                        </button>
                                                    </>
                                                )}
                                            </div>
                                        </div>
                                    </div>
                                ))}
                            </div>
                        )}
                    </div>

                    {/* 단관 이슈 목록 */}
                    <div className="segment-issues-section">
                        <div className="section-header">
                            <h2>🔧 단관 이슈 목록</h2>
                        </div>
                        
                        {segmentIssues.length === 0 ? (
                            <div className="no-issues">
                                <p>등록된 단관 이슈가 없습니다.</p>
                            </div>
                        ) : (
                            <div className="issues-list">
                                {segmentIssues.map(issue => (
                                    <div key={issue.id} className="issue-card segment-issue">
                                        <div className="issue-header">
                                            <div className="issue-title">
                                                <span className="segment-id">단관 #{issue.segment_id}</span>
                                                {issue.issue_type && (
                                                    <span className="issue-type-badge">{issue.issue_type}</span>
                                                )}
                                            </div>
                                            <div className="issue-badges">
                                                <span 
                                                    className="severity-badge"
                                                    style={{ backgroundColor: getSeverityColor(issue.severity) }}
                                                >
                                                    {issue.severity}
                                                </span>
                                                <span 
                                                    className="status-badge"
                                                    style={{ backgroundColor: getStatusColor(issue.status) }}
                                                >
                                                    {issue.status}
                                                </span>
                                            </div>
                                        </div>
                                        <div className="issue-content">
                                            <p>{issue.issue_description}</p>
                                            {(issue.length_change || issue.new_length || issue.material_change) && (
                                                <div className="issue-changes">
                                                    {issue.length_change && (
                                                        <span className="change-item">
                                                            길이 변경: {issue.length_change > 0 ? '+' : ''}{issue.length_change}mm
                                                        </span>
                                                    )}
                                                    {issue.new_length && (
                                                        <span className="change-item">
                                                            최종 길이: {issue.new_length}mm
                                                        </span>
                                                    )}
                                                    {issue.material_change && (
                                                        <span className="change-item">
                                                            재질 변경: {issue.material_change}
                                                        </span>
                                                    )}
                                                </div>
                                            )}
                                        </div>
                                        <div className="issue-footer">
                                            <div className="issue-meta">
                                                <span>보고자: {issue.reported_by}</span>
                                                <span>등록일: {new Date(issue.reported_at).toLocaleDateString()}</span>
                                            </div>
                                            <div className="issue-actions">
                                                {issue.status !== 'resolved' && (
                                                    <>
                                                        <button 
                                                            className="btn btn-sm btn-warning"
                                                            onClick={() => handleUpdateIssueStatus(issue.id, 'segment', 'in_progress')}
                                                        >
                                                            진행중으로 변경
                                                        </button>
                                                        <button 
                                                            className="btn btn-sm btn-success"
                                                            onClick={() => handleUpdateIssueStatus(issue.id, 'segment', 'resolved')}
                                                        >
                                                            완료로 변경
                                                        </button>
                                                    </>
                                                )}
                                            </div>
                                        </div>
                                    </div>
                                ))}
                            </div>
                        )}
                    </div>
                </>
            )}

            {/* 도면 이슈 생성 모달 */}
            {showCreateDrawingIssue && (
                <div className="modal-overlay">
                    <div className="modal-content">
                        <div className="modal-header">
                            <h3>📋 도면 이슈 등록</h3>
                            <button 
                                className="modal-close"
                                onClick={() => setShowCreateDrawingIssue(false)}
                            >
                                ×
                            </button>
                        </div>
                        <form onSubmit={handleCreateDrawingIssue}>
                            <div className="form-group">
                                <label>구역 *</label>
                                <select 
                                    value={drawingIssueForm.area}
                                    onChange={(e) => setDrawingIssueForm({...drawingIssueForm, area: e.target.value})}
                                    required
                                >
                                    <option value="">구역 선택</option>
                                    {availableAreas.map(area => (
                                        <option key={area} value={area}>{area}</option>
                                    ))}
                                </select>
                            </div>
                            <div className="form-group">
                                <label>도면명 *</label>
                                <select 
                                    value={drawingIssueForm.drawing_name}
                                    onChange={(e) => setDrawingIssueForm({...drawingIssueForm, drawing_name: e.target.value})}
                                    required
                                >
                                    <option value="">도면 선택</option>
                                    {availableDrawings.map(drawing => (
                                        <option key={drawing} value={drawing}>{drawing}</option>
                                    ))}
                                </select>
                            </div>
                            <div className="form-group">
                                <label>이슈 설명 *</label>
                                <textarea 
                                    value={drawingIssueForm.issue_description}
                                    onChange={(e) => setDrawingIssueForm({...drawingIssueForm, issue_description: e.target.value})}
                                    placeholder="도면 전반적인 문제점을 상세히 설명해주세요..."
                                    rows="4"
                                    required
                                />
                            </div>
                            <div className="form-group">
                                <label>심각도</label>
                                <select 
                                    value={drawingIssueForm.severity}
                                    onChange={(e) => setDrawingIssueForm({...drawingIssueForm, severity: e.target.value})}
                                >
                                    <option value="low">낮음</option>
                                    <option value="medium">보통</option>
                                    <option value="high">높음</option>
                                    <option value="critical">긴급</option>
                                </select>
                            </div>
                            <div className="modal-actions">
                                <button type="button" className="btn btn-secondary" onClick={() => setShowCreateDrawingIssue(false)}>
                                    취소
                                </button>
                                <button type="submit" className="btn btn-primary">
                                    등록
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}

            {/* 단관 이슈 생성 모달 */}
            {showCreateSegmentIssue && (
                <div className="modal-overlay">
                    <div className="modal-content">
                        <div className="modal-header">
                            <h3>🔧 단관 이슈 등록</h3>
                            <button 
                                className="modal-close"
                                onClick={() => setShowCreateSegmentIssue(false)}
                            >
                                ×
                            </button>
                        </div>
                        <form onSubmit={handleCreateSegmentIssue}>
                            <div className="form-group">
                                <label>단관 선택 *</label>
                                <select 
                                    value={segmentIssueForm.segment_id}
                                    onChange={(e) => setSegmentIssueForm({...segmentIssueForm, segment_id: e.target.value})}
                                    required
                                >
                                    <option value="">단관 선택</option>
                                    {segments.map(segment => (
                                        <option key={segment.id} value={segment.id}>
                                            {segment.area} - {segment.drawing_name} - {segment.line_no} ({segment.length_mm}mm)
                                        </option>
                                    ))}
                                </select>
                            </div>
                            <div className="form-group">
                                <label>이슈 유형</label>
                                <select 
                                    value={segmentIssueForm.issue_type}
                                    onChange={(e) => setSegmentIssueForm({...segmentIssueForm, issue_type: e.target.value})}
                                >
                                    <option value="cutting">절단</option>
                                    <option value="installation">설치</option>
                                    <option value="material">재질</option>
                                    <option value="routing">라우팅</option>
                                    <option value="other">기타</option>
                                </select>
                            </div>
                            <div className="form-group">
                                <label>이슈 설명 *</label>
                                <textarea 
                                    value={segmentIssueForm.issue_description}
                                    onChange={(e) => setSegmentIssueForm({...segmentIssueForm, issue_description: e.target.value})}
                                    placeholder="단관에서 발생한 문제점을 상세히 설명해주세요..."
                                    rows="4"
                                    required
                                />
                            </div>
                            <div className="form-row">
                                <div className="form-group">
                                    <label>길이 변경량 (mm)</label>
                                    <input 
                                        type="number"
                                        step="0.1"
                                        value={segmentIssueForm.length_change}
                                        onChange={(e) => setSegmentIssueForm({...segmentIssueForm, length_change: e.target.value})}
                                        placeholder="예: -30 (30mm 절단)"
                                    />
                                </div>
                                <div className="form-group">
                                    <label>최종 길이 (mm)</label>
                                    <input 
                                        type="number"
                                        step="0.1"
                                        value={segmentIssueForm.new_length}
                                        onChange={(e) => setSegmentIssueForm({...segmentIssueForm, new_length: e.target.value})}
                                        placeholder="예: 1470"
                                    />
                                </div>
                            </div>
                            <div className="form-group">
                                <label>재질 변경</label>
                                <input 
                                    type="text"
                                    value={segmentIssueForm.material_change}
                                    onChange={(e) => setSegmentIssueForm({...segmentIssueForm, material_change: e.target.value})}
                                    placeholder="변경된 재질 정보"
                                />
                            </div>
                            <div className="form-group">
                                <label>심각도</label>
                                <select 
                                    value={segmentIssueForm.severity}
                                    onChange={(e) => setSegmentIssueForm({...segmentIssueForm, severity: e.target.value})}
                                >
                                    <option value="low">낮음</option>
                                    <option value="medium">보통</option>
                                    <option value="high">높음</option>
                                    <option value="critical">긴급</option>
                                </select>
                            </div>
                            <div className="modal-actions">
                                <button type="button" className="btn btn-secondary" onClick={() => setShowCreateSegmentIssue(false)}>
                                    취소
                                </button>
                                <button type="submit" className="btn btn-primary">
                                    등록
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}

            {/* 이슈 리포트 모달 */}
            {issueReport && (
                <div className="modal-overlay">
                    <div className="modal-content large">
                        <div className="modal-header">
                            <h3>📊 이슈 리포트</h3>
                            <button 
                                className="modal-close"
                                onClick={() => setIssueReport(null)}
                            >
                                ×
                            </button>
                        </div>
                        <div className="report-content">
                            <div className="report-summary">
                                <h4>전체 요약</h4>
                                <p>총 이슈: {issueReport.total_issues}개</p>
                                <p>생성일: {new Date(issueReport.report_generated_at).toLocaleString()}</p>
                            </div>
                            
                            <div className="report-section">
                                <h4>도면 이슈 통계</h4>
                                <div className="report-stats">
                                    <p>총 개수: {issueReport.drawing_issues.total}</p>
                                    <div className="stats-breakdown">
                                        {Object.entries(issueReport.drawing_issues.by_status).map(([status, count]) => (
                                            <span key={status} className="stat-item">
                                                {status}: {count}개
                                            </span>
                                        ))}
                                    </div>
                                </div>
                            </div>

                            <div className="report-section">
                                <h4>단관 이슈 통계</h4>
                                <div className="report-stats">
                                    <p>총 개수: {issueReport.segment_issues.total}</p>
                                    <div className="stats-breakdown">
                                        {Object.entries(issueReport.segment_issues.by_status).map(([status, count]) => (
                                            <span key={status} className="stat-item">
                                                {status}: {count}개
                                            </span>
                                        ))}
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div className="modal-actions">
                            <button className="btn btn-secondary" onClick={() => setIssueReport(null)}>
                                닫기
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};

export default PipeIssueManagementPage;
