import { useMemo, useState } from 'react';
import { toNumberSet } from '../lib/setUtils';

export interface HoverStateInput {
  hoveredMmsiSet: number[];
  hoveredFleetMmsiSet: number[];
  hoveredPairMmsiSet: number[];
  hoveredFleetOwnerKey: string | null;
  highlightedMmsiSet: number[];
}

export function useHoverState(input: HoverStateInput) {
  const {
    hoveredMmsiSet,
    hoveredFleetMmsiSet,
    hoveredPairMmsiSet,
    hoveredFleetOwnerKey,
    highlightedMmsiSet,
  } = input;

  // Internal deck hover states
  const [hoveredDeckMmsiSet, setHoveredDeckMmsiSet] = useState<number[]>([]);
  const [hoveredDeckPairMmsiSet, setHoveredDeckPairMmsiSet] = useState<number[]>([]);
  const [hoveredDeckFleetOwnerKey, setHoveredDeckFleetOwnerKey] = useState<string | null>(null);
  const [hoveredDeckFleetMmsiSet, setHoveredDeckFleetMmsiSet] = useState<number[]>([]);
  const [hoveredZoneId, setHoveredZoneId] = useState<string | null>(null);

  // Derived sets
  const hoveredMmsiSetRef = useMemo(() => toNumberSet(hoveredMmsiSet), [hoveredMmsiSet]);
  const hoveredFleetMmsiSetRef = useMemo(() => toNumberSet(hoveredFleetMmsiSet), [hoveredFleetMmsiSet]);
  const hoveredPairMmsiSetRef = useMemo(() => toNumberSet(hoveredPairMmsiSet), [hoveredPairMmsiSet]);
  const externalHighlightedSetRef = useMemo(() => toNumberSet(highlightedMmsiSet), [highlightedMmsiSet]);
  const hoveredDeckMmsiSetRef = useMemo(() => toNumberSet(hoveredDeckMmsiSet), [hoveredDeckMmsiSet]);
  const hoveredDeckPairMmsiSetRef = useMemo(() => toNumberSet(hoveredDeckPairMmsiSet), [hoveredDeckPairMmsiSet]);
  const hoveredDeckFleetMmsiSetRef = useMemo(() => toNumberSet(hoveredDeckFleetMmsiSet), [hoveredDeckFleetMmsiSet]);

  const hoveredFleetOwnerKeys = useMemo(() => {
    const keys = new Set<string>();
    if (hoveredFleetOwnerKey) keys.add(hoveredFleetOwnerKey);
    if (hoveredDeckFleetOwnerKey) keys.add(hoveredDeckFleetOwnerKey);
    return keys;
  }, [hoveredFleetOwnerKey, hoveredDeckFleetOwnerKey]);

  return {
    // Internal states + setters
    hoveredDeckMmsiSet,
    setHoveredDeckMmsiSet,
    hoveredDeckPairMmsiSet,
    setHoveredDeckPairMmsiSet,
    hoveredDeckFleetOwnerKey,
    setHoveredDeckFleetOwnerKey,
    hoveredDeckFleetMmsiSet,
    setHoveredDeckFleetMmsiSet,
    hoveredZoneId,
    setHoveredZoneId,
    // Derived sets
    hoveredMmsiSetRef,
    hoveredFleetMmsiSetRef,
    hoveredPairMmsiSetRef,
    externalHighlightedSetRef,
    hoveredDeckMmsiSetRef,
    hoveredDeckPairMmsiSetRef,
    hoveredDeckFleetMmsiSetRef,
    hoveredFleetOwnerKeys,
  };
}
