import { useRouter } from 'expo-router'
import type { SearchIntent } from '../intents'
import { MenuIconButton, MenuSearchField } from '../MenuBar'

// renderSearch — two distinct presentations: (a) magnifier icon in the
// trailing cluster (tap to expand / tap to route); (b) expanded inline morph
// with close control.

export function RenderSearchToggle({
  intent,
  onToggle,
  reduceMotion,
  size,
  tint,
}: {
  intent: SearchIntent
  onToggle: () => void
  reduceMotion?: boolean
  size?: number
  tint?: string
}) {
  const router = useRouter()
  const onPress = () => {
    if (intent.mode === 'route') {
      if (intent.routeTo) router.push(intent.routeTo)
      else intent.onRouteTo?.()
      return
    }
    onToggle()
  }
  return (
    <MenuIconButton
      icon="search"
      onPress={onPress}
      accessibilityLabel={intent.accessibilityLabel ?? 'Search'}
      accessibilityHint={intent.accessibilityHint ?? intent.placeholder}
      reduceMotion={reduceMotion}
      size={size}
      tint={tint}
    />
  )
}

export function RenderSearchField({
  intent,
  onClose,
  reduceMotion,
  size,
  tint,
}: {
  intent: SearchIntent
  onClose: () => void
  reduceMotion?: boolean
  size?: number
  tint?: string
}) {
  return (
    <>
      <MenuSearchField
        search={{
          placeholder: intent.placeholder,
          value: intent.value ?? '',
          onChangeText: intent.onChangeText ?? (() => {}),
        }}
        autoFocus
      />
      <MenuIconButton
        icon="x"
        onPress={onClose}
        accessibilityLabel="Close search"
        reduceMotion={reduceMotion}
        size={size}
        tint={tint}
      />
    </>
  )
}
