import { useCallback, useMemo } from 'react';
import { usePersistedState } from '../../../shared/hooks/usePersistedState';
import type { VesselGroup } from '../model/types';
import { MAX_VESSEL_GROUPS } from '../model/types';

export interface VesselGroupsState {
  groups: VesselGroup[];
  /** 동명 그룹 존재 시 갱신, 신규 시 추가. 10개 초과 시 경고 문자열 반환 */
  saveGroup: (name: string, mmsis: number[]) => string | null;
  deleteGroup: (id: string) => void;
  applyGroup: (group: VesselGroup) => void;
}

export function useVesselGroups(
  userId: number | null,
  setMmsis: (mmsis: Set<number>) => void,
): VesselGroupsState {
  const [rawGroups, setRawGroups] = usePersistedState<VesselGroup[]>(userId, 'vesselGroups', []);

  const groups = useMemo(
    () => [...rawGroups].sort((a, b) => b.updatedAt - a.updatedAt),
    [rawGroups],
  );

  const saveGroup = useCallback(
    (name: string, mmsis: number[]): string | null => {
      const trimmed = name.trim();
      if (!trimmed) return '그룹명을 입력해주세요';

      let warning: string | null = null;

      setRawGroups((prev) => {
        const existing = prev.find((g) => g.name === trimmed);
        if (existing) {
          return prev.map((g) =>
            g.id === existing.id ? { ...g, mmsis, updatedAt: Date.now() } : g,
          );
        }
        if (prev.length >= MAX_VESSEL_GROUPS) {
          warning = `최대 ${MAX_VESSEL_GROUPS}개까지 저장 가능합니다`;
          return prev;
        }
        return [...prev, { id: Date.now().toString(36), name: trimmed, mmsis, updatedAt: Date.now() }];
      });

      return warning;
    },
    [setRawGroups],
  );

  const deleteGroup = useCallback(
    (id: string) => {
      setRawGroups((prev) => prev.filter((g) => g.id !== id));
    },
    [setRawGroups],
  );

  const applyGroup = useCallback(
    (group: VesselGroup) => {
      setMmsis(new Set(group.mmsis));
    },
    [setMmsis],
  );

  return { groups, saveGroup, deleteGroup, applyGroup };
}
