import { useCallback, type RefObject } from 'react'
import type { PartyMember } from '../game'
import {
  selectDirectionalPartyTarget,
  selectDirectPartyTarget,
  selectRelativePartyTarget,
  type NavigateAction,
} from '../combat/targeting'
import type { InputAction } from '../input'

type PartyTargetingOptions = {
  getParty: () => PartyMember[]
  selectedIdRef: RefObject<string>
  setSelectedTargetId: (id: string) => void
  columns: number
  livingOnly?: boolean
  relativeLivingOnly?: boolean
  directionalLivingOnly?: boolean
  directLivingOnly?: boolean
  directTargetGroup?: number
}

export function usePartyTargeting({
  getParty,
  selectedIdRef,
  setSelectedTargetId,
  columns,
  livingOnly = true,
  relativeLivingOnly = livingOnly,
  directionalLivingOnly = livingOnly,
  directLivingOnly = livingOnly,
  directTargetGroup = 0,
}: PartyTargetingOptions) {
  const selectRelativeTarget = useCallback((direction: -1 | 1) => {
    const targetId = selectRelativePartyTarget(getParty(), selectedIdRef.current, direction, {
      livingOnly: relativeLivingOnly,
    })
    if (targetId) setSelectedTargetId(targetId)
  }, [getParty, relativeLivingOnly, selectedIdRef, setSelectedTargetId])

  const selectDirectionalTarget = useCallback((action: InputAction) => {
    const targetId = selectDirectionalPartyTarget(
      getParty(),
      selectedIdRef.current,
      action as NavigateAction,
      columns,
      { livingOnly: directionalLivingOnly },
    )
    if (targetId) setSelectedTargetId(targetId)
  }, [columns, directionalLivingOnly, getParty, selectedIdRef, setSelectedTargetId])

  const selectDirectTarget = useCallback((slot: number) => {
    const targetId = selectDirectPartyTarget(getParty(), slot, {
      livingOnly: directLivingOnly,
      targetGroup: directTargetGroup,
    })
    if (targetId) setSelectedTargetId(targetId)
  }, [directLivingOnly, directTargetGroup, getParty, setSelectedTargetId])

  return {
    selectRelativeTarget,
    selectDirectionalTarget,
    selectDirectTarget,
  }
}
