/**
 * 선박 목록 컴포넌트
 */

import { SORT_OPTIONS } from '../utils/constants.js';
import { escapeSelector, formatDistance, formatSpeed, getTypeLabel } from '../utils/helpers.js';

export class VesselList {
    constructor(containerId = 'vesselList') {
        this.containerId = containerId;
        this.container = null;
        this.vesselGroups = new Map();
        this.activeVesselId = null;
        this.selectedTracks = new Set();
        this.sortBy = SORT_OPTIONS.COUNT;
        this.isCustomDetectionMode = false;
    }

    /**
     * 초기화
     */
    init() {
        this.container = document.getElementById(this.containerId);
        if (!this.container) {
            console.error(`Container element not found: ${this.containerId}`);
        }
    }

    /**
     * 선박별로 궤적 그룹화
     */
    groupTracksByVessel(tracks) {
        this.vesselGroups.clear();
        
        tracks.forEach(track => {
            const vesselId = track.vesselId;
            if (!this.vesselGroups.has(vesselId)) {
                this.vesselGroups.set(vesselId, []);
            }
            this.vesselGroups.get(vesselId).push(track);
        });
        
        // 각 그룹 내에서 시간순 정렬
        this.vesselGroups.forEach((tracks, vesselId) => {
            tracks.sort((a, b) => new Date(b.detectedAt) - new Date(a.detectedAt));
        });
    }

    /**
     * 선박 목록 렌더링
     */
    render() {
        if (!this.container) return;
        
        if (this.vesselGroups.size === 0) {
            this.container.innerHTML = `
                <div class="no-data">
                    검출된 비정상 궤적이 없습니다.
                </div>
            `;
            return;
        }
        
        const vesselData = this.prepareVesselData();
        this.sortVesselData(vesselData);
        
        this.container.innerHTML = vesselData.map(data => 
            this.renderVesselGroup(data)
        ).join('');
        
        this.attachEventListeners();
    }

    /**
     * 선박 데이터 준비
     */
    prepareVesselData() {
        return Array.from(this.vesselGroups.entries()).map(([vesselId, tracks]) => {
            const totalDistance = tracks.reduce((sum, t) => sum + (parseFloat(t.distanceNm) || 0), 0);
            const totalTime = tracks.reduce((sum, t) => {
                const dist = parseFloat(t.distanceNm) || 0;
                const speed = parseFloat(t.avgSpeed) || 1;
                return sum + (dist / speed);
            }, 0);
            const avgSpeed = totalTime > 0 ? totalDistance / totalTime : 0;
            const latestTime = new Date(tracks[0].detectedAt);
            
            return {
                vesselId,
                tracks,
                totalDistance,
                avgSpeed,
                latestTime,
                count: tracks.length
            };
        });
    }

    /**
     * 선박 데이터 정렬
     */
    sortVesselData(vesselData) {
        switch (this.sortBy) {
            case SORT_OPTIONS.COUNT:
                vesselData.sort((a, b) => b.count - a.count);
                break;
            case SORT_OPTIONS.DISTANCE:
                vesselData.sort((a, b) => b.totalDistance - a.totalDistance);
                break;
            case SORT_OPTIONS.SPEED:
                vesselData.sort((a, b) => b.avgSpeed - a.avgSpeed);
                break;
            case SORT_OPTIONS.RECENT:
                vesselData.sort((a, b) => b.latestTime - a.latestTime);
                break;
        }
    }

    /**
     * 선박 그룹 렌더링
     */
    renderVesselGroup({vesselId, tracks, totalDistance, avgSpeed}) {
        const typeCounts = {};
        tracks.forEach(track => {
            const type = track.abnormalType;
            typeCounts[type] = (typeCounts[type] || 0) + 1;
        });
        
        const topTypes = Object.entries(typeCounts)
            .sort((a, b) => b[1] - a[1])
            .slice(0, 2)
            .map(([type]) => `
                <span class="abnormal-type-badge type-${type} ms-1" style="font-size: 0.7em; padding: 2px 6px;">
                    ${getTypeLabel(type)}
                </span>
            `).join('');
        
        const isActive = this.activeVesselId === vesselId;
        const headerClass = isActive ? 'vessel-header active' : 'vessel-header';
        const tracksDisplay = isActive ? 'block' : 'none';
        
        return `
            <div class="vessel-group" data-vessel-id="${vesselId}">
                <div class="${headerClass}" data-vessel-id="${vesselId}">
                    <div class="vessel-info">
                        <div class="vessel-id">
                            ${vesselId}
                            ${topTypes}
                        </div>
                        <div class="vessel-stats">
                            총 거리: ${formatDistance(totalDistance)} | 평균 속도: ${formatSpeed(avgSpeed)}
                        </div>
                    </div>
                    <span class="vessel-count">${tracks.length}</span>
                </div>
                <div class="vessel-tracks" id="tracks-${escapeSelector(vesselId)}" style="display: ${tracksDisplay};">
                    ${this.renderTrackList(tracks, vesselId)}
                </div>
            </div>
        `;
    }

    /**
     * 트랙 목록 렌더링
     */
    renderTrackList(tracks, vesselId) {
        return tracks.map(track => {
            const isSelected = this.selectedTracks.has(String(track.id));
            const selectedClass = isSelected ? 'selected' : '';
            
            return `
                <div class="track-item ${selectedClass}" 
                     data-track-id="${track.id}" 
                     data-vessel-id="${vesselId}">
                    ${this.isCustomDetectionMode ? `
                        <input type="checkbox" class="track-checkbox" 
                               data-track-id="${track.id}" 
                               data-vessel-id="${vesselId}"
                               ${isSelected ? 'checked' : ''}
                               onclick="event.stopPropagation()">
                    ` : ''}
                    <div style="display: flex; justify-content: space-between; align-items: start; flex: 1;">
                        <div>
                            <div style="font-weight: 500;">
                                ${new Date(track.timeBucket).toLocaleString('ko-KR')}
                            </div>
                            <div style="font-size: 0.85em; color: #6c757d;">
                                ${formatDistance(track.distanceNm)} | ${formatSpeed(track.avgSpeed)}
                            </div>
                        </div>
                        <span class="abnormal-type-badge type-${track.abnormalType}">
                            ${getTypeLabel(track.abnormalType)}
                        </span>
                    </div>
                </div>
            `;
        }).join('');
    }

    /**
     * 이벤트 리스너 연결
     */
    attachEventListeners() {
        // 선박 헤더 클릭
        this.container.querySelectorAll('.vessel-header').forEach(header => {
            header.addEventListener('click', (e) => {
                const vesselId = header.dataset.vesselId;
                this.toggleVessel(vesselId);
            });
        });
        
        // 트랙 아이템 클릭
        if (!this.isCustomDetectionMode) {
            this.container.querySelectorAll('.track-item').forEach(item => {
                item.addEventListener('click', (e) => {
                    if (!e.target.classList.contains('track-checkbox')) {
                        const trackId = item.dataset.trackId;
                        const vesselId = item.dataset.vesselId;
                        this.selectTrack(trackId, vesselId);
                    }
                });
            });
        }
        
        // 체크박스 변경
        if (this.isCustomDetectionMode) {
            this.container.querySelectorAll('.track-checkbox').forEach(checkbox => {
                checkbox.addEventListener('change', () => {
                    this.onCheckboxChange?.();
                });
            });
        }
    }

    /**
     * 선박 토글
     */
    toggleVessel(vesselId) {
        const tracksEl = document.getElementById(`tracks-${escapeSelector(vesselId)}`);
        const header = this.container.querySelector(`.vessel-header[data-vessel-id="${vesselId}"]`);
        
        if (this.activeVesselId === vesselId) {
            // 닫기
            tracksEl.style.display = 'none';
            header.classList.remove('active');
            this.activeVesselId = null;
            this.selectedTracks.clear();
        } else {
            // 다른 모든 선박 접기
            this.container.querySelectorAll('.vessel-tracks').forEach(el => {
                el.style.display = 'none';
            });
            this.container.querySelectorAll('.vessel-header').forEach(el => {
                el.classList.remove('active');
            });
            
            // 선택한 선박 열기
            tracksEl.style.display = 'block';
            header.classList.add('active');
            this.activeVesselId = vesselId;
            
            // 첫 번째 트랙 자동 선택
            const tracks = this.vesselGroups.get(vesselId);
            if (tracks && tracks.length > 0) {
                this.selectedTracks.clear();
                this.selectedTracks.add(String(tracks[0].id));
                this.updateTrackSelection();
            }
        }
        
        this.onVesselToggle?.(vesselId);
    }

    /**
     * 트랙 선택
     */
    selectTrack(trackId, vesselId) {
        // 현재 활성 그룹이 아니면 먼저 활성화
        if (this.activeVesselId !== vesselId) {
            this.toggleVessel(vesselId);
        }
        
        // 선택 상태 토글
        trackId = String(trackId);
        if (this.selectedTracks.has(trackId)) {
            this.selectedTracks.delete(trackId);
        } else {
            this.selectedTracks.clear();
            this.selectedTracks.add(trackId);
        }
        
        this.updateTrackSelection();
        this.onTrackSelect?.(trackId, vesselId);
    }

    /**
     * 트랙 선택 UI 업데이트
     */
    updateTrackSelection() {
        this.container.querySelectorAll('.track-item').forEach(item => {
            const trackId = item.dataset.trackId;
            item.classList.toggle('selected', this.selectedTracks.has(trackId));
        });
    }

    /**
     * 정렬 기준 설정
     */
    setSortBy(sortBy) {
        this.sortBy = sortBy;
        this.render();
    }

    /**
     * 사용자 정의 검출 모드 설정
     */
    setCustomDetectionMode(enabled) {
        this.isCustomDetectionMode = enabled;
    }

    /**
     * 선택된 체크박스 트랙 가져오기
     */
    getSelectedCheckboxTracks() {
        const selected = new Set();
        this.container.querySelectorAll('.track-checkbox:checked').forEach(checkbox => {
            const trackId = checkbox.dataset.trackId;
            if (trackId) {
                selected.add(trackId);
            }
        });
        return selected;
    }

    /**
     * 이벤트 핸들러 설정
     */
    setEventHandlers(handlers) {
        if (handlers.onVesselToggle) {
            this.onVesselToggle = handlers.onVesselToggle;
        }
        if (handlers.onTrackSelect) {
            this.onTrackSelect = handlers.onTrackSelect;
        }
        if (handlers.onCheckboxChange) {
            this.onCheckboxChange = handlers.onCheckboxChange;
        }
    }

    /**
     * 로딩 상태 표시
     */
    showLoading() {
        if (this.container) {
            this.container.innerHTML = `
                <div class="loading">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Loading...</span>
                    </div>
                    <div class="mt-2">데이터를 불러오는 중...</div>
                </div>
            `;
        }
    }
}