/**
 * 장비 필터 훅 (모달 항적조회 전용)
 *
 * 항적 데이터에서 장비(신호원천)별로 ON/OFF 토글 관리
 * - 기본값: 최우선순위 장비만 ON
 * - 통합선박 전용 기능
 */

import { useState, useMemo, useCallback, useEffect } from 'react';
import {
  SIGNAL_SOURCE_CODE_AIS,
  SIGNAL_SOURCE_CODE_D_MF_HF,
  SIGNAL_SOURCE_CODE_ENAV,
  SIGNAL_SOURCE_CODE_RADAR,
  SIGNAL_SOURCE_CODE_VPASS,
  SIGNAL_SOURCE_CODE_VTS_AIS,
} from '../../types/constants';

/**
 * 신호 원천별 설정
 */
const SIGNAL_CONFIGS = {
  [SIGNAL_SOURCE_CODE_AIS]: { key: 'A', signalSourceCode: SIGNAL_SOURCE_CODE_AIS, name: 'AIS', shortName: 'AIS', background: '#C2A7DC', priority: 2, displayOrder: 1 },
  [SIGNAL_SOURCE_CODE_VPASS]: { key: 'V', signalSourceCode: SIGNAL_SOURCE_CODE_VPASS, name: 'V-Pass', shortName: 'V-P', background: '#8FAEFC', priority: 3, displayOrder: 2 },
  [SIGNAL_SOURCE_CODE_ENAV]: { key: 'E', signalSourceCode: SIGNAL_SOURCE_CODE_ENAV, name: 'E-Nav', shortName: 'E-N', background: '#74B2F0', priority: 4, displayOrder: 3 },
  [SIGNAL_SOURCE_CODE_VTS_AIS]: { key: 'T', signalSourceCode: SIGNAL_SOURCE_CODE_VTS_AIS, name: 'VTS-AIS', shortName: 'VTS', background: '#4190DF', priority: 1, displayOrder: 4 },
  [SIGNAL_SOURCE_CODE_D_MF_HF]: { key: 'D', signalSourceCode: SIGNAL_SOURCE_CODE_D_MF_HF, name: 'D-MF/HF', shortName: 'DMF', background: '#459EF6', priority: 5, displayOrder: 5 },
  [SIGNAL_SOURCE_CODE_RADAR]: { key: 'R', signalSourceCode: SIGNAL_SOURCE_CODE_RADAR, name: 'VTS-RT', shortName: 'RT', background: '#4577F6', priority: 6, displayOrder: 6 },
};

/**
 * 항적 데이터에서 사용된 장비 목록 추출
 */
const extractEquipmentsFromTracks = (tracks) => {
  const equipmentCounts = new Map();

  tracks.forEach(track => {
    const sigSrcCd = track.sigSrcCd;
    if (sigSrcCd && SIGNAL_CONFIGS[sigSrcCd]) {
      const pointCount = track.geometry?.length || track.timestampsMs?.length || 0;
      equipmentCounts.set(sigSrcCd, (equipmentCounts.get(sigSrcCd) || 0) + pointCount);
    }
  });

  return equipmentCounts;
};

/**
 * 장비 필터 훅
 *
 * @param {Array} tracks 항적 데이터 배열
 * @returns {Object} 장비 필터 관련 상태 및 함수
 */
export const useEquipmentFilter = (tracks) => {
  const [enabledSet, setEnabledSet] = useState(new Set());

  const equipmentData = useMemo(() => {
    return extractEquipmentsFromTracks(tracks);
  }, [tracks]);

  const equipments = useMemo(() => {
    const items = [];

    equipmentData.forEach((count, sigSrcCd) => {
      const config = SIGNAL_CONFIGS[sigSrcCd];
      if (config) {
        items.push({
          ...config,
          isEnabled: enabledSet.has(sigSrcCd),
          trackCount: count,
        });
      }
    });

    return items.sort((a, b) => a.displayOrder - b.displayOrder);
  }, [equipmentData, enabledSet]);

  const highestPriorityEquipment = useMemo(() => {
    if (equipments.length === 0) return null;
    return equipments.reduce((prev, curr) => (curr.priority < prev.priority ? curr : prev));
  }, [equipments]);

  // 트랙 데이터 변경 시 기본값 설정
  useEffect(() => {
    if (equipmentData.size > 0 && enabledSet.size === 0) {
      const sigSrcCodes = Array.from(equipmentData.keys());
      const sorted = sigSrcCodes.sort((a, b) => {
        const priorityA = SIGNAL_CONFIGS[a]?.priority ?? 999;
        const priorityB = SIGNAL_CONFIGS[b]?.priority ?? 999;
        return priorityA - priorityB;
      });
      if (sorted.length > 0) {
        setEnabledSet(new Set([sorted[0]]));
      }
    }
  }, [equipmentData]);

  const toggleEquipment = useCallback((signalSourceCode) => {
    setEnabledSet(prev => {
      const next = new Set(prev);
      if (next.has(signalSourceCode)) {
        if (next.size > 1) {
          next.delete(signalSourceCode);
        }
      } else {
        next.add(signalSourceCode);
      }
      return next;
    });
  }, []);

  const enableAll = useCallback(() => {
    setEnabledSet(new Set(equipmentData.keys()));
  }, [equipmentData]);

  const resetToDefault = useCallback(() => {
    if (highestPriorityEquipment) {
      setEnabledSet(new Set([highestPriorityEquipment.signalSourceCode]));
    }
  }, [highestPriorityEquipment]);

  const hasMultipleEquipments = equipments.length > 1;

  const filteredTracks = useMemo(() => {
    if (enabledSet.size === 0) return tracks;
    return tracks.filter(track => enabledSet.has(track.sigSrcCd));
  }, [tracks, enabledSet]);

  return {
    equipments,
    enabledEquipments: enabledSet,
    toggleEquipment,
    enableAll,
    resetToDefault,
    hasMultipleEquipments,
    filteredTracks,
  };
};

export default useEquipmentFilter;
