import React, { memo, useMemo } from 'react';
import { Box, Text } from 'ink';
import TextInput from 'ink-text-input';
import { getCommandCompletions, getCommandTooltip } from '../commands.js';

export interface InputBarProps {
  value: string;
  onChange: (value: string) => void;
  onSubmit: (value: string) => void;
  isLoading?: boolean;
  placeholder?: string;
}

export const InputBar = memo(function InputBar({
  value,
  onChange,
  onSubmit,
  isLoading = false,
  placeholder = 'Type a message...',
}: InputBarProps): React.ReactElement {
  const completions = useMemo(() => {
    if (!value.startsWith('/')) {return [];}
    return getCommandCompletions(value);
  }, [value]);

  const tooltip = useMemo(() => {
    if (!value.startsWith('/')) {return null;}
    return getCommandTooltip(value);
  }, [value]);

  const showTooltip = value.startsWith('/') && (tooltip || completions.length > 1);

  return (
    <Box flexDirection="column">
      {/* Tooltip bar */}
      {showTooltip && (
        <Box paddingX={2} height={1} justifyContent="center">
          <Text color="gray">
            {tooltip
              ? `→ ${tooltip}`
              : `${completions.length} commands (Tab)`
            }
          </Text>
        </Box>
      )}

      {/* Input bar */}
      <Box borderStyle="single" borderColor="blue" paddingX={1}>
        <Text color="blue">{'> '}</Text>
        {isLoading ? (
          <Text color="gray">Thinking...</Text>
        ) : (
          <TextInput
            value={value}
            onChange={onChange}
            onSubmit={onSubmit}
            placeholder={placeholder}
          />
        )}
      </Box>
    </Box>
  );
});
