/**
 * 리플레이 메인 스토어
 * 참조: src/tracking/stores/trackingStore.ts
 *
 * 리플레이 상태 관리 (쿼리, 필터, 선박 상태 등)
 */
import { create } from 'zustand';
import { subscribeWithSelector } from 'zustand/middleware';
import {
  ConnectionState,
  VesselState,
  FilterModuleType,
  DEFAULT_FILTER_MODULE,
} from '../types/replay.types';
import useMergedTrackStore from './mergedTrackStore';
import usePlaybackTrailStore from './playbackTrailStore';
import {
  SIGNAL_SOURCE_CODE_AIS,
  SIGNAL_SOURCE_CODE_ENAV,
  SIGNAL_SOURCE_CODE_VPASS,
  SIGNAL_SOURCE_CODE_VTS_AIS,
  SIGNAL_SOURCE_CODE_RADAR,
  SIGNAL_SOURCE_CODE_D_MF_HF,
  SIGNAL_KIND_CODE_FISHING,
  SIGNAL_KIND_CODE_KCGV,
  SIGNAL_KIND_CODE_PASSENGER,
  SIGNAL_KIND_CODE_CARGO,
  SIGNAL_KIND_CODE_TANKER,
  SIGNAL_KIND_CODE_GOV,
  SIGNAL_KIND_CODE_NORMAL,
  SIGNAL_KIND_CODE_BUOY,
} from '../../types/constants';

/**
 * 초기 신호원 필터 (모두 활성화)
 */
const initialSigSrcCdFilter = new Set([
  SIGNAL_SOURCE_CODE_AIS,
  SIGNAL_SOURCE_CODE_ENAV,
  SIGNAL_SOURCE_CODE_VPASS,
  SIGNAL_SOURCE_CODE_VTS_AIS,
  SIGNAL_SOURCE_CODE_RADAR,
  SIGNAL_SOURCE_CODE_D_MF_HF,
]);

/**
 * 초기 선종 필터 (모두 활성화)
 */
const initialShipKindCodeFilter = new Set([
  SIGNAL_KIND_CODE_FISHING,
  SIGNAL_KIND_CODE_KCGV,
  SIGNAL_KIND_CODE_PASSENGER,
  SIGNAL_KIND_CODE_CARGO,
  SIGNAL_KIND_CODE_TANKER,
  SIGNAL_KIND_CODE_GOV,
  SIGNAL_KIND_CODE_NORMAL,
  SIGNAL_KIND_CODE_BUOY,
]);

/**
 * ReplayStore
 */
const useReplayStore = create(
  subscribeWithSelector((set, get) => ({
    // ===== 쿼리/연결 상태 =====
    currentQuery: null, // TrackQueryRequest
    queryId: null,
    connectionState: ConnectionState.DISCONNECTED,
    queryCompleted: false,

    // ===== 진행률 =====
    progress: 0, // 0-100
    receivedChunks: 0,
    totalChunks: null,
    lastReceivedTimestamp: null,

    // ===== 필터 =====
    sigSrcCdFilter: initialSigSrcCdFilter,
    shipKindCodeFilter: initialShipKindCodeFilter,

    // ===== 선박 상태 =====
    vesselStates: new Map(), // Map<vesselId, VesselState>
    deletedVesselIds: new Set(), // 레거시 호환
    selectedVesselIds: new Set(), // 레거시 호환

    // ===== 필터 모듈 (3계층) =====
    filterModules: {
      [FilterModuleType.CUSTOM]: { ...DEFAULT_FILTER_MODULE }, // 아이콘
      [FilterModuleType.PATH]: {
        // 항적 라인
        showNormal: false,
        showSelected: false,
        showDeleted: false,
      },
      [FilterModuleType.LABEL]: {
        // 라벨
        showNormal: true,
        showSelected: false,
        showDeleted: false,
      },
    },

    // ===== 뷰포트 =====
    currentViewport: null,
    currentZoomLevel: 10,

    // ===== 하이라이트 =====
    highlightedVesselId: null,

    // ===== 액션: 쿼리/연결 =====

    setCurrentQuery: (query) => set({ currentQuery: query }),

    setQueryId: (queryId) => set({ queryId }),

    setConnectionState: (state) => set({ connectionState: state }),

    setQueryCompleted: (completed) => set({ queryCompleted: completed }),

    // ===== 액션: 진행률 =====

    updateProgress: (received, total, timestamp) =>
      set({
        receivedChunks: received,
        totalChunks: total,
        lastReceivedTimestamp: timestamp,
        progress: total > 0 ? (received / total) * 100 : 0,
      }),

    setProgress: (progress) => set({ progress }),

    // ===== 액션: 필터 =====

    toggleSigSrcCd: (code) => {
      const filter = get().sigSrcCdFilter;
      const newFilter = new Set(filter);
      if (newFilter.has(code)) {
        newFilter.delete(code);
      } else {
        newFilter.add(code);
      }
      set({ sigSrcCdFilter: newFilter });
    },

    toggleShipKindCode: (code) => {
      const filter = get().shipKindCodeFilter;
      const newFilter = new Set(filter);
      if (newFilter.has(code)) {
        newFilter.delete(code);
      } else {
        newFilter.add(code);
      }
      set({ shipKindCodeFilter: newFilter });
    },

    // ===== 액션: 선박 상태 =====

    setVesselState: (vesselId, state) => {
      const currentState = get();
      const newVesselStates = new Map(currentState.vesselStates);

      if (state === VesselState.NORMAL) {
        newVesselStates.delete(vesselId);
      } else {
        newVesselStates.set(vesselId, state);
      }

      // 레거시 호환용 Set 업데이트
      const newDeletedVesselIds = new Set(currentState.deletedVesselIds);
      const newSelectedVesselIds = new Set(currentState.selectedVesselIds);

      // 기존 상태 제거
      newDeletedVesselIds.delete(vesselId);
      newSelectedVesselIds.delete(vesselId);

      // 새 상태 추가
      if (state === VesselState.DELETED) {
        newDeletedVesselIds.add(vesselId);
      } else if (state === VesselState.SELECTED) {
        newSelectedVesselIds.add(vesselId);
      }

      set({
        vesselStates: newVesselStates,
        deletedVesselIds: newDeletedVesselIds,
        selectedVesselIds: newSelectedVesselIds,
      });
    },

    getVesselState: (vesselId) => {
      const state = get().vesselStates.get(vesselId);
      if (state) return state;

      // 레거시 호환
      if (get().deletedVesselIds.has(vesselId)) return VesselState.DELETED;
      if (get().selectedVesselIds.has(vesselId)) return VesselState.SELECTED;
      return VesselState.NORMAL;
    },

    toggleVesselState: (vesselId, targetState) => {
      const currentVesselState = get().getVesselState(vesselId);
      if (currentVesselState === targetState) {
        get().setVesselState(vesselId, VesselState.NORMAL);
      } else {
        get().setVesselState(vesselId, targetState);
      }
    },

    clearVesselState: (vesselId) => {
      get().setVesselState(vesselId, VesselState.NORMAL);
    },

    // ===== 액션: 필터 모듈 =====

    updateFilterModule: (moduleId, config) => {
      set((state) => ({
        filterModules: {
          ...state.filterModules,
          [moduleId]: {
            ...state.filterModules[moduleId],
            ...config,
          },
        },
      }));
    },

    setFilterModuleAll: (moduleId, enabled) => {
      set((state) => ({
        filterModules: {
          ...state.filterModules,
          [moduleId]: {
            showNormal: enabled,
            showSelected: enabled,
            showDeleted: enabled,
          },
        },
      }));
    },

    // ===== 액션: 하이라이트 =====

    setHighlightedVesselId: (vesselId) => set({ highlightedVesselId: vesselId }),

    // ===== 액션: 뷰포트 =====

    setViewport: (viewport) => set({ currentViewport: viewport }),

    setZoomLevel: (zoom) => set({ currentZoomLevel: zoom }),

    // ===== 액션: 초기화 =====

    reset: () => {
      // mergedTrackStore 클리어
      useMergedTrackStore.getState().clear();

      // playbackTrailStore 초기화 (setEnabled(false)가 trails와 frameIndex도 클리어)
      usePlaybackTrailStore.getState().setEnabled(false);

      set({
        currentQuery: null,
        queryId: null,
        connectionState: ConnectionState.DISCONNECTED,
        queryCompleted: false,
        progress: 0,
        receivedChunks: 0,
        totalChunks: null,
        lastReceivedTimestamp: null,
        vesselStates: new Map(),
        deletedVesselIds: new Set(),
        selectedVesselIds: new Set(),
        sigSrcCdFilter: initialSigSrcCdFilter,
        shipKindCodeFilter: initialShipKindCodeFilter,
        highlightedVesselId: null,
        filterModules: {
          [FilterModuleType.CUSTOM]: { ...DEFAULT_FILTER_MODULE },
          [FilterModuleType.PATH]: {
            showNormal: false,
            showSelected: false,
            showDeleted: false,
          },
          [FilterModuleType.LABEL]: {
            showNormal: true,
            showSelected: false,
            showDeleted: false,
          },
        },
      });
    },
  }))
);

export default useReplayStore;
