import type { ScrollBoxRenderable } from "@opentui/core"
import { Index, Show } from "solid-js"
import type { ClawSlashOption } from "./autocomplete-types"
import { SplitBorder } from "@tui/component/border"
import { selectedForeground, useTheme } from "@tui/context/theme"

type PopupProps = {
  visible: boolean
  options: ClawSlashOption[]
  selected: number
  position: { x: number; y: number; width: number }
  height: number
  moveTo: (index: number) => void
  select: () => void
  scrollRef: (el: ScrollBoxRenderable) => void
}

export function AutocompletePopup(props: PopupProps) {
  const { theme } = useTheme()

  return (
    <box
      visible={props.visible}
      position="absolute"
      top={props.position.y - props.height}
      left={props.position.x}
      width={props.position.width}
      zIndex={100}
      {...SplitBorder}
      borderColor={theme.border}
    >
      <scrollbox
        ref={(r: ScrollBoxRenderable) => props.scrollRef(r)}
        backgroundColor={theme.backgroundMenu}
        height={props.height}
        scrollbarOptions={{ visible: false }}
      >
        <Index
          each={props.options}
          fallback={
            <box paddingLeft={1} paddingRight={1}>
              <text fg={theme.textMuted}>No matching commands</text>
            </box>
          }
        >
          {(option, index) => (
            <box
              paddingLeft={1}
              paddingRight={1}
              backgroundColor={index === props.selected ? theme.primary : undefined}
              flexDirection="row"
              onMouseDown={() => props.moveTo(index)}
              onMouseUp={() => props.select()}
            >
              <text fg={index === props.selected ? selectedForeground(theme) : theme.text} flexShrink={0}>
                {option().display}
              </text>
              <Show when={option().description}>
                <text fg={index === props.selected ? selectedForeground(theme) : theme.textMuted} wrapMode="none">
                  {" "}
                  {option().description}
                </text>
              </Show>
            </box>
          )}
        </Index>
      </scrollbox>
    </box>
  )
}
