import { useState, useEffect, useRef, useMemo, useCallback } from 'react';
import type { VesselAnalysisDto } from '../types';
import { fetchVesselAnalysis } from '../services/vesselAnalysis';
import type { AnalysisStats } from '../services/vesselAnalysis';

export type { AnalysisStats };

const POLL_INTERVAL_MS = 5 * 60_000; // 5분
const STALE_MS = 30 * 60_000; // 30분

export interface UseVesselAnalysisResult {
  analysisMap: Map<string, VesselAnalysisDto>;
  stats: AnalysisStats;
  clusters: Map<number, string[]>;
  isLoading: boolean;
  lastUpdated: number;
}

const EMPTY_STATS: AnalysisStats = {
  total: 0, critical: 0, high: 0, medium: 0, low: 0,
  dark: 0, spoofing: 0, clusterCount: 0,
  gearGroups: 0, gearCount: 0,
};

export function useVesselAnalysis(enabled: boolean): UseVesselAnalysisResult {
  const mapRef = useRef<Map<string, VesselAnalysisDto>>(new Map());
  const statsRef = useRef<AnalysisStats>(EMPTY_STATS);
  const [version, setVersion] = useState(0);
  const [isLoading, setIsLoading] = useState(false);
  const [lastUpdated, setLastUpdated] = useState(0);

  const doFetch = useCallback(async () => {
    if (!enabled) return;
    setIsLoading(true);
    try {
      const data = await fetchVesselAnalysis();
      const now = Date.now();
      const map = mapRef.current;

      // stale 제거
      for (const [mmsi, dto] of map) {
        const ts = new Date(dto.timestamp).getTime();
        if (now - ts > STALE_MS) map.delete(mmsi);
      }

      // 새 결과 merge
      for (const item of data.items) {
        map.set(item.mmsi, item);
      }

      // 서버에서 계산된 stats 직접 사용
      statsRef.current = data.stats;

      setLastUpdated(now);
      setVersion(v => v + 1);
    } catch {
      // 에러 시 기존 데이터 유지 (graceful degradation)
    } finally {
      setIsLoading(false);
    }
  }, [enabled]);

  useEffect(() => {
    doFetch();
    const t = setInterval(doFetch, POLL_INTERVAL_MS);
    return () => clearInterval(t);
  }, [doFetch]);

  const analysisMap = mapRef.current;

  // clusters는 vesselList/마커 렌더링에 필요 — 경량 순회이므로 유지
  const clusters = useMemo((): Map<number, string[]> => {
    const result = new Map<number, string[]>();
    for (const [mmsi, dto] of analysisMap) {
      const cid = dto.algorithms.cluster.clusterId;
      if (cid < 0) continue;
      const arr = result.get(cid);
      if (arr) arr.push(mmsi);
      else result.set(cid, [mmsi]);
    }
    return result;
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [version]);

  return { analysisMap, stats: statsRef.current, clusters, isLoading, lastUpdated };
}
