/**
 * Sequential Passage 관리자 컴포넌트
 */

import { PassageAPI, APIHelper } from '../api/gis-api.js';
import { normalizeZoneId, parseVesselId } from '../utils/gis-utils.js';

export class GISSequentialManager {
    constructor() {
        this.zones = [];
        this.maxZones = 3;
        this.results = null;
        this.mode = 'sequential';
        this.zoneType = 'GRID';
    }

    /**
     * 구역 추가
     */
    addZone(zoneId) {
        const normalized = normalizeZoneId(zoneId);
        
        if (!normalized) {
            return { success: false, message: '구역 ID를 입력하세요' };
        }
        
        if (this.zones.length >= this.maxZones) {
            return { success: false, message: `최대 ${this.maxZones}개 구역만 선택 가능합니다` };
        }
        
        if (this.zones.includes(normalized)) {
            return { success: false, message: '이미 추가된 구역입니다' };
        }
        
        this.zones.push(normalized);
        this.onZonesChange?.(this.zones);
        
        return { success: true, zone: normalized };
    }

    /**
     * 구역 제거
     */
    removeZone(index) {
        if (index >= 0 && index < this.zones.length) {
            const removed = this.zones.splice(index, 1)[0];
            this.onZonesChange?.(this.zones);
            return removed;
        }
        return null;
    }

    /**
     * 전체 구역 초기화
     */
    clearZones() {
        this.zones = [];
        this.onZonesChange?.(this.zones);
    }

    /**
     * 순차 통과 검색
     */
    async searchSequential(startTime, endTime) {
        if (this.zones.length !== 3) {
            throw new Error('순차 통과 검색은 정확히 3개의 구역이 필요합니다');
        }
        
        const params = {
            type: this.zoneType,
            zoneIds: this.zones,
            startTime: APIHelper.formatTimestamp(startTime),
            endTime: APIHelper.formatTimestamp(endTime)
        };
        
        try {
            const results = await PassageAPI.searchSequential(params);
            this.results = results;
            return this.processResults(results);
        } catch (error) {
            console.error('Sequential search failed:', error);
            throw error;
        }
    }

    /**
     * 전체 구역 통과 검색
     */
    async searchAllZones(startTime, endTime) {
        if (this.zones.length === 0) {
            throw new Error('최소 1개 이상의 구역을 선택하세요');
        }
        
        const params = {
            type: this.zoneType,
            zoneIds: this.zones,
            startTime: APIHelper.formatTimestamp(startTime),
            endTime: APIHelper.formatTimestamp(endTime)
        };
        
        try {
            const results = await PassageAPI.searchAllZones(params);
            this.results = results;
            return this.processResults(results);
        } catch (error) {
            console.error('All zones search failed:', error);
            throw error;
        }
    }

    /**
     * 검색 실행
     */
    async search(mode, type, startTime, endTime) {
        this.mode = mode;
        this.zoneType = type;
        
        if (mode === 'sequential') {
            return this.searchSequential(startTime, endTime);
        } else {
            return this.searchAllZones(startTime, endTime);
        }
    }

    /**
     * 결과 처리
     */
    processResults(results) {
        if (!results) return [];
        
        // 결과 구조 정규화
        const vessels = results.passages || results.vessels || [];
        
        return vessels.map(vessel => {
            // 다양한 필드명 처리
            const sigSrcCd = vessel.sigSrcCd || vessel.sig_src_cd;
            const targetId = vessel.targetId || vessel.target_id;
            const vesselId = `${sigSrcCd}_${targetId}`;
            
            // 선박 정보 추출
            const vesselInfo = vessel.vesselInfo || {};
            const shipName = vesselInfo.shipName || 
                           vesselInfo.ship_name || 
                           vessel.ship_name ||
                           null;
            
            return {
                vesselId,
                sigSrcCd,
                targetId,
                shipName,
                vesselInfo,
                // 추가 정보가 있다면 포함
                passages: vessel.passages,
                firstTime: vessel.firstTime || vessel.first_time,
                lastTime: vessel.lastTime || vessel.last_time
            };
        });
    }

    /**
     * 구역 렌더링 (HTML)
     */
    renderZones() {
        if (this.zones.length === 0) {
            return '<small class="text-muted">선택된 구역이 없습니다</small>';
        }
        
        return this.zones.map((zone, index) => `
            <span class="zone-tag">
                ${zone}
                <span class="remove-zone" data-index="${index}" style="cursor: pointer;">
                    <i class="bi bi-x"></i>
                </span>
            </span>
        `).join('');
    }

    /**
     * 검색 결과 렌더링 (HTML)
     */
    renderResults() {
        const processed = this.getProcessedResults();
        
        if (processed.length === 0) {
            return '<div class="text-muted text-center p-3">검색 결과가 없습니다</div>';
        }
        
        let html = `<h6 class="mb-3">${processed.length}척의 선박 발견</h6>`;
        
        processed.forEach(vessel => {
            const displayName = vessel.shipName || vessel.vesselId;
            const subtitle = vessel.shipName ? vessel.vesselId : '선박명 없음';
            
            html += `
                <div class="vessel-item" data-vessel-id="${vessel.vesselId}" style="cursor: pointer;">
                    <div class="vessel-info">
                        <strong>${displayName}</strong>
                        <small class="text-muted d-block">${subtitle}</small>
                        ${vessel.firstTime ? `
                            <small class="text-muted">
                                ${new Date(vessel.firstTime).toLocaleString('ko-KR')}
                            </small>
                        ` : ''}
                    </div>
                </div>
            `;
        });
        
        return html;
    }

    /**
     * 검색 파라미터 검증
     */
    validateSearchParams(startTime, endTime) {
        const errors = [];
        
        if (!startTime || !endTime) {
            errors.push('시작 시간과 종료 시간을 모두 입력하세요');
        }
        
        if (new Date(startTime) >= new Date(endTime)) {
            errors.push('종료 시간은 시작 시간보다 이후여야 합니다');
        }
        
        if (this.zones.length === 0) {
            errors.push('최소 1개 이상의 구역을 선택하세요');
        }
        
        if (this.mode === 'sequential' && this.zones.length !== 3) {
            errors.push('순차 통과 모드는 정확히 3개의 구역이 필요합니다');
        }
        
        return {
            valid: errors.length === 0,
            errors
        };
    }

    /**
     * 설정 변경
     */
    setMode(mode) {
        this.mode = mode;
    }

    setZoneType(type) {
        this.zoneType = type;
    }

    setMaxZones(max) {
        this.maxZones = max;
    }

    /**
     * 이벤트 핸들러
     */
    setEventHandlers(handlers) {
        this.onZonesChange = handlers.onZonesChange;
        this.onResultSelect = handlers.onResultSelect;
    }

    /**
     * 상태 초기화
     */
    reset() {
        this.zones = [];
        this.results = null;
        this.onZonesChange?.(this.zones);
    }

    // Getters
    getZones() {
        return [...this.zones];
    }

    getZoneCount() {
        return this.zones.length;
    }

    hasZone(zoneId) {
        return this.zones.includes(normalizeZoneId(zoneId));
    }

    canAddZone() {
        return this.zones.length < this.maxZones;
    }

    getResults() {
        return this.results;
    }

    getProcessedResults() {
        return this.results ? this.processResults(this.results) : [];
    }

    getMode() {
        return this.mode;
    }

    getZoneType() {
        return this.zoneType;
    }
}