import {useEffect, useRef} from 'react'
import {type TextInput, View} from 'react-native'
import {useLingui} from '@lingui/react/macro'

import {HITSLOP_10} from '#/lib/constants'
import {mergeRefs} from '#/lib/merge-refs'
import {listenFocusSearch} from '#/state/events'
import {useEnableSquareButtons} from '#/state/preferences/enable-square-buttons'
import {atoms as a, useTheme} from '#/alf'
import {Button, ButtonIcon} from '#/components/Button'
import * as TextField from '#/components/forms/TextField'
import {MagnifyingGlass_Stroke2_Corner0_Rounded as MagnifyingGlassIcon} from '#/components/icons/MagnifyingGlass'
import {TimesLarge_Stroke2_Corner0_Rounded as X} from '#/components/icons/Times'
import {IS_NATIVE} from '#/env'

type Props = Omit<TextField.InputProps, 'label'> & {
  label?: TextField.InputProps['label']
  /**
   * Called when the user presses the (X) button
   */
  onClearText?: () => void
  hotkey?: boolean
  ref?: React.Ref<TextInput>
}

export function SearchInput({
  value,
  label,
  onClearText,
  hotkey,
  ref,
  ...rest
}: Props) {
  const t = useTheme()
  const {t: l} = useLingui()
  const showClear = value && value.length > 0
  const internalRef = useRef<TextInput>(null)

  useEffect(() => {
    if (!hotkey) return
    return listenFocusSearch(() => {
      internalRef.current?.focus()
    })
  }, [hotkey])

  const enableSquareButtons = useEnableSquareButtons()

  return (
    <View style={[a.w_full, a.relative]}>
      <TextField.Root>
        <TextField.Icon icon={MagnifyingGlassIcon} />
        <TextField.Input
          inputRef={mergeRefs([internalRef, ref])}
          label={label || l`Search`}
          value={value}
          placeholder={l`Search`}
          returnKeyType="search"
          keyboardAppearance={t.scheme}
          selectTextOnFocus={IS_NATIVE}
          autoFocus={false}
          accessibilityRole="search"
          autoCorrect={false}
          autoComplete="off"
          autoCapitalize="none"
          style={[
            showClear
              ? {
                  paddingRight: 24,
                }
              : {},
          ]}
          {...rest}
        />
      </TextField.Root>

      {showClear && (
        <View
          style={[
            a.absolute,
            a.z_20,
            a.my_auto,
            a.inset_0,
            a.justify_center,
            a.pr_sm,
            {left: 'auto'},
          ]}>
          <Button
            testID="searchTextInputClearBtn"
            onPress={onClearText}
            label={l`Clear search query`}
            hitSlop={HITSLOP_10}
            size="tiny"
            shape={enableSquareButtons ? 'square' : 'round'}
            variant="ghost"
            color="secondary">
            <ButtonIcon icon={X} size="xs" />
          </Button>
        </View>
      )}
    </View>
  )
}
